ToFaRev sessions

ToFaRev review

srl-labs/vrnetlab · 1c29a33a3761

completed · 41 messages · 63 tool calls

Last snapshot:

Download session JSON · Full transcript

Final review

# ToFaRev review

**Partial review. Some analysis remains unfinished.**

Source inspection only; PR code, tests, and benchmarks were not executed.

| Finding | Location |
| --- | --- |
| **P4 - New README paragraph documents `FOS_EXIT_ON_BOOTSTRAP_ERROR` instead of the primary `FTNT_` spelling** | [fortinet/fortigate/docker/README.md:134-139](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/fortigate/docker/README.md#L134-L139) |
| **P4 - Duplicated `completion = (FOSCliState.CMD_PROMPT,)` assignment in `state_case`** | [fortinet/tests/test_common_stack_boundaries.py:105-108](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/tests/test_common_stack_boundaries.py#L105-L108) |

## P4 - New README paragraph documents `FOS_EXIT_ON_BOOTSTRAP_ERROR` instead of the primary `FTNT_` spelling

**Location:** [fortinet/fortigate/docker/README.md:134-139](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/fortigate/docker/README.md#L134-L139)

**Problem:** The paragraph added by this PR instructs users to set `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, while the rest of the same document (`docker/README.md` line 311) and the top-level `fortigate/README.md` (lines 97 and 471) document `FTNT_EXIT_ON_BOOTSTRAP_ERROR` as the canonical spelling. Both spellings work because [`env.py`](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/common/env.py#L1-L1) `_candidate_names` resolves aliases, but the new paragraph introduces a second, inconsistent documented spelling for the same variable.

**Trigger:** A user follows the new paragraph, sets `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, then searches the documentation for that name and finds only the `FTNT_` spelling elsewhere.

**Impact:** Documentation inconsistency only; runtime behavior is unchanged because the aliasing accepts both names.

**Suggested correction:** Change line 139 to `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` (or add a one-line note that the `FOS_` prefix is an accepted alias), keeping the documented public interface consistent with the rest of both READMEs.


## P4 - Duplicated `completion = (FOSCliState.CMD_PROMPT,)` assignment in `state_case`

**Location:** [fortinet/tests/test_common_stack_boundaries.py:105-108](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/tests/test_common_stack_boundaries.py#L105-L108)

**Problem:** In the `state_case` helper introduced by this PR, the `if` branch (`FOSCliState.CREDENTIAL_REJECTED`, `FOSCliState.PROVIDE_USERNAME`) and the `elif` branch (`FOSCliState.CREDENTIAL_ACCEPTED`, `FOSCliState.SESSION_LOST`, `FOSCliState.CMD_PROMPT_ECHO`) assign the identical value `completion = (FOSCliState.CMD_PROMPT,)`.

**Trigger:** Any future maintainer editing the completion mapping for these states.

**Impact:** Cosmetic maintainability only; behavior is correct. The duplication invites an edit to one branch but not the other.

**Suggested correction:** Merge the two branches into a single condition covering all five states with one assignment of `completion = (FOSCliState.CMD_PROMPT,)`.


## Coverage

- Source-only review; no tests were executed and no formatter was run. The snapshot manifest reports incomplete: true, so repository-level coverage is incomplete despite full reading of all 18 changed head files, the full diff, all six test files, context-only `features/license.py` and [`env.py`](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/common/env.py#L1-L1), and both READMEs.
- `standards.json` is empty; no repository rules were applied.
- No GitHub permalink roots were supplied in this session; file references use path:line inline code and the publisher can attach links.
- Pre-existing issues deliberately not reported as PR findings: the `FTNT_FORTIGUARD_HOOKS` omission from the top-level README env table and the pre-existing filter_startup_config_blocks code in `features/startup_config.py`, since the diff only adds _startup_config_commands.
- The stable_match re-run in [`terminal.py`](https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/fortinet/common/terminal.py#L1-L1) and the id(spec)-keyed _cleanup_retries map were investigated and judged acceptable (defensive re-run on a bounded 1 `MiB` buffer; retry-map lifetime bounded by cleanup completion), so neither is reported as a finding.

---
Powered by <a href="https://tokenfactory.nebius.com/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/hellt/tofarev/11341daf301af9b89b711528df08d0a9e9139bca/assets/nebius-token-factory-dark.svg"><img src="https://raw.githubusercontent.com/hellt/tofarev/11341daf301af9b89b711528df08d0a9e9139bca/assets/nebius-token-factory-light.svg" alt="Nebius Token Factory" height="22" align="absmiddle"></picture></a>

```json
{
  "version": 1,
  "findings": [
    {
      "priority": "P4",
      "title": "New README paragraph documents `FOS_EXIT_ON_BOOTSTRAP_ERROR` instead of the primary `FTNT_` spelling",
      "location": {
        "revision": "head",
        "path": "fortinet/fortigate/docker/README.md",
        "start": 134,
        "end": 139
      },
      "problem": "The paragraph added by this PR instructs users to set `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, while the rest of the same document (`docker/README.md` line 311) and the top-level `fortigate/README.md` (lines 97 and 471) document `FTNT_EXIT_ON_BOOTSTRAP_ERROR` as the canonical spelling. Both spellings work because `env.py` `_candidate_names` resolves aliases, but the new paragraph introduces a second, inconsistent documented spelling for the same variable.",
      "trigger": "A user follows the new paragraph, sets `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, then searches the documentation for that name and finds only the `FTNT_` spelling elsewhere.",
      "impact": "Documentation inconsistency only; runtime behavior is unchanged because the aliasing accepts both names.",
      "suggestion": "Change line 139 to `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` (or add a one-line note that the `FOS_` prefix is an accepted alias), keeping the documented public interface consistent with the rest of both READMEs."
    },
    {
      "priority": "P4",
      "title": "Duplicated `completion = (FOSCliState.CMD_PROMPT,)` assignment in `state_case`",
      "location": {
        "revision": "head",
        "path": "fortinet/tests/test_common_stack_boundaries.py",
        "start": 105,
        "end": 108
      },
      "problem": "In the `state_case` helper introduced by this PR, the `if` branch (`FOSCliState.CREDENTIAL_REJECTED`, `FOSCliState.PROVIDE_USERNAME`) and the `elif` branch (`FOSCliState.CREDENTIAL_ACCEPTED`, `FOSCliState.SESSION_LOST`, `FOSCliState.CMD_PROMPT_ECHO`) assign the identical value `completion = (FOSCliState.CMD_PROMPT,)`.",
      "trigger": "Any future maintainer editing the completion mapping for these states.",
      "impact": "Cosmetic maintainability only; behavior is correct. The duplication invites an edit to one branch but not the other.",
      "suggestion": "Merge the two branches into a single condition covering all five states with one assignment of `completion = (FOSCliState.CMD_PROMPT,)`."
    }
  ],
  "coverage": {
    "complete": false,
    "notes": [
      "Source-only review; no tests were executed and no formatter was run. The snapshot manifest reports incomplete: true, so repository-level coverage is incomplete despite full reading of all 18 changed head files, the full diff, all six test files, context-only `features/license.py` and `env.py`, and both READMEs.",
      "`standards.json` is empty; no repository rules were applied.",
      "No GitHub permalink roots were supplied in this session; file references use path:line inline code and the publisher can attach links.",
      "Pre-existing issues deliberately not reported as PR findings: the `FTNT_FORTIGUARD_HOOKS` omission from the top-level README env table and the pre-existing filter_startup_config_blocks code in `features/startup_config.py`, since the diff only adds _startup_config_commands.",
      "The stable_match re-run in `terminal.py` and the id(spec)-keyed _cleanup_retries map were investigated and judged acceptable (defensive re-run on a bounded 1 `MiB` buffer; retry-map lifetime bounded by cleanup completion), so neither is reported as a finding."
    ]
  }
}
```
User · 1
Review the read-only PR snapshot at /source.
Read standards.json and its referenced rules, then diff.txt and relevant head/ and base/ files. Track all 18 changed paths from the diff. Complete checks for each changed path and relevant callers, tests, docs, and schema before finalizing. Source-only review can be complete without executing tests; disclose that limitation. Use read offsets for truncated output and group independent tool calls. Use glob/grep for surrounding code. Return the trusted result schema.
Head: 1c29a33a37619b7547248e3b845130ba1f5f8ad0. Comparison base: 11dd16f88e2e5990de1061be498577af6c5d3552. Target base: 11dd16f88e2e5990de1061be498577af6c5d3552.
GitHub permalink roots: head=https://github.com/srl-labs/vrnetlab/blob/1c29a33a37619b7547248e3b845130ba1f5f8ad0/; base=https://github.com/srl-labs/vrnetlab/blob/11dd16f88e2e5990de1061be498577af6c5d3552/.
Snapshot incomplete: true. The full inventory and omission details are in manifest.json; consult it when needed. Report incomplete coverage.
Message metadata
{
  "role": "user",
  "id": "msg_1a1d103be001tgPKtIdGJM73lG",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716192190
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 2
step-start
{
  "type": "step-start",
  "id": "prt_1a1d113e9001Ol7YDqSax1a1kt",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1060c001AP7pRDr1Ds8efX"
}
Reasoning
Let me start by exploring the snapshot structure.
read · error

Input

{
  "filePath": "/source"
}

Output

The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{"permission":"*","action":"allow","pattern":"*"},{"permission":"read","pattern":"*","action":"allow"},{"permission":"read","pattern":"*.env","action":"ask"},{"permission":"read","pattern":"*.env.*","action":"ask"},{"permission":"read","pattern":"*.env.example","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"}]
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d1145f001UPFk9gHGRSBplw",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1060c001AP7pRDr1Ds8efX",
  "callID": "call_c4decc7f43c841d3a32ed886",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source"
    },
    "error": "The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{\"permission\":\"*\",\"action\":\"allow\",\"pattern\":\"*\"},{\"permission\":\"read\",\"pattern\":\"*\",\"action\":\"allow\"},{\"permission\":\"read\",\"pattern\":\"*.env\",\"action\":\"ask\"},{\"permission\":\"read\",\"pattern\":\"*.env.*\",\"action\":\"ask\"},{\"permission\":\"read\",\"pattern\":\"*.env.example\",\"action\":\"allow\"},{\"permission\":\"*\",\"action\":\"deny\",\"pattern\":\"*\"},{\"permission\":\"read\",\"pattern\":\"*\",\"action\":\"deny\"},{\"permission\":\"read\",\"pattern\":\"source/*\",\"action\":\"allow\"},{\"permission\":\"*\",\"action\":\"deny\",\"pattern\":\"*\"},{\"permission\":\"read\",\"pattern\":\"*\",\"action\":\"deny\"},{\"permission\":\"read\",\"pattern\":\"source/*\",\"action\":\"allow\"}]",
    "time": {
      "start": 1793716196455,
      "end": 1793716196462
    }
  }
}
read · completed

Input

{
  "filePath": "/source/standards.json"
}

Output

<path>/source/standards.json</path>
<type>file</type>
<content>
1: []

(End of file - total 1 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d114920018FgEe5zPIrcIgt",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1060c001AP7pRDr1Ds8efX",
  "callID": "call_705a5cac2b304de1b58544f6",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/standards.json"
    },
    "output": "<path>/source/standards.json</path>\n<type>file</type>\n<content>\n1: []\n\n(End of file - total 1 lines)\n</content>",
    "title": "source/standards.json",
    "metadata": {
      "preview": "[]",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/standards.json",
        "text": "[]",
        "lineStart": 1,
        "lineEnd": 1,
        "totalLines": 1,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716196504,
      "end": 1793716196528
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d114b5001YEBejTtDyVUPjL",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1060c001AP7pRDr1Ds8efX",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3314,
    "input": 3281,
    "output": 23,
    "reasoning": 10,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d1060c001AP7pRDr1Ds8efX",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716192780,
    "completed": 1793716196539
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3314,
    "input": 3281,
    "output": 23,
    "reasoning": 10,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 3
step-start
{
  "type": "step-start",
  "id": "prt_1a1d11b95001M9Bx2Uw6rw68b5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d114bf001b7PRnRynOkPtjP"
}
Reasoning
standards.json is empty (no rules). Now read manifest.json and diff.txt.
read · completed

Input

{
  "filePath": "/source/manifest.json"
}

Output

<path>/source/manifest.json</path>
<type>file</type>
<content>
1: {
2:   "version": 1,
3:   "head": "1c29a33a37619b7547248e3b845130ba1f5f8ad0",
4:   "base": "11dd16f88e2e5990de1061be498577af6c5d3552",
5:   "mergeBase": "11dd16f88e2e5990de1061be498577af6c5d3552",
6:   "changed": [
7:     {
8:       "status": "M",
9:       "path": "fortinet/common/cli_commands.py"
10:     },
11:     {
12:       "status": "M",
13:       "path": "fortinet/common/common.py"
14:     },
15:     {
16:       "status": "M",
17:       "path": "fortinet/common/features/base.py"
18:     },
19:     {
20:       "status": "M",
21:       "path": "fortinet/common/features/credentials.py"
22:     },
23:     {
24:       "status": "M",
25:       "path": "fortinet/common/features/pki.py"
26:     },
27:     {
28:       "status": "M",
29:       "path": "fortinet/common/features/startup_config.py"
30:     },
31:     {
32:       "status": "M",
33:       "path": "fortinet/common/fos_cli_driver.py"
34:     },
35:     {
36:       "status": "M",
37:       "path": "fortinet/common/fos_commander.py"
38:     },
39:     {
40:       "status": "M",
41:       "path": "fortinet/common/launch.py"
42:     },
43:     {
44:       "status": "M",
45:       "path": "fortinet/common/terminal.py"
46:     },
47:     {
48:       "status": "M",
49:       "path": "fortinet/fortigate/README.md"
50:     },
51:     {
52:       "status": "M",
53:       "path": "fortinet/fortigate/docker/README.md"
54:     },
55:     {
56:       "status": "A",
57:       "path": "fortinet/tests/test_common_admin_credentials.py"
58:     },
59:     {
60:       "status": "A",
61:       "path": "fortinet/tests/test_common_recovery.py"
62:     },
63:     {
64:       "status": "A",
65:       "path": "fortinet/tests/test_common_scope_errors.py"
66:     },
67:     {
68:       "status": "M",
69:       "path": "fortinet/tests/test_common_stack_boundaries.py"
70:     },
71:     {
72:       "status": "M",
73:       "path": "fortinet/tests/test_common_stack_parsing.py"
74:     },
75:     {
76:       "status": "M",
77:       "path": "fortinet/tests/test_common_terminal_driver.py"
78:     }
79:   ],
80:   "files": [
81:     {
82:       "revision": "head",
83:       "path": "fortinet/common/cli_commands.py",
84:       "bytes": 6467,
85:       "lines": 207
86:     },
87:     {
88:       "revision": "head",
89:       "path": "fortinet/common/common.py",
90:       "bytes": 3700,
91:       "lines": 92
92:     },
93:     {
94:       "revision": "head",
95:       "path": "fortinet/common/features/base.py",
96:       "bytes": 3298,
97:       "lines": 119
98:     },
99:     {
100:       "revision": "head",
101:       "path": "fortinet/common/features/credentials.py",
102:       "bytes": 4094,
103:       "lines": 90
104:     },
105:     {
106:       "revision": "head",
107:       "path": "fortinet/common/features/pki.py",
108:       "bytes": 17660,
109:       "lines": 471
110:     },
111:     {
112:       "revision": "head",
113:       "path": "fortinet/common/features/startup_config.py",
114:       "bytes": 4247,
115:       "lines": 117
116:     },
117:     {
118:       "revision": "head",
119:       "path": "fortinet/common/fos_cli_driver.py",
120:       "bytes": 13311,
121:       "lines": 331
122:     },
123:     {
124:       "revision": "head",
125:       "path": "fortinet/common/fos_commander.py",
126:       "bytes": 27921,
127:       "lines": 687
128:     },
129:     {
130:       "revision": "head",
131:       "path": "fortinet/common/launch.py",
132:       "bytes": 18457,
133:       "lines": 506
134:     },
135:     {
136:       "revision": "head",
137:       "path": "fortinet/common/terminal.py",
138:       "bytes": 13228,
139:       "lines": 398
140:     },
141:     {
142:       "revision": "head",
143:       "path": "fortinet/fortigate/docker/README.md",
144:       "bytes": 24337,
145:       "lines": 500
146:     },
147:     {
148:       "revision": "head",
149:       "path": "fortinet/fortigate/README.md",
150:       "bytes": 25304,
151:       "lines": 497
152:     },
153:     {
154:       "revision": "head",
155:       "path": "fortinet/tests/test_common_admin_credentials.py",
156:       "bytes": 6689,
157:       "lines": 154
158:     },
159:     {
160:       "revision": "head",
161:       "path": "fortinet/tests/test_common_recovery.py",
162:       "bytes": 13626,
163:       "lines": 292
164:     },
165:     {
166:       "revision": "head",
167:       "path": "fortinet/tests/test_common_scope_errors.py",
168:       "bytes": 7676,
169:       "lines": 154
170:     },
171:     {
172:       "revision": "head",
173:       "path": "fortinet/tests/test_common_stack_boundaries.py",
174:       "bytes": 15421,
175:       "lines": 349
176:     },
177:     {
178:       "revision": "head",
179:       "path": "fortinet/tests/test_common_stack_parsing.py",
180:       "bytes": 10427,
181:       "lines": 268
182:     },
183:     {
184:       "revision": "head",
185:       "path": "fortinet/tests/test_common_terminal_driver.py",
186:       "bytes": 15190,
187:       "lines": 332
188:     },
189:     {
190:       "revision": "head",
191:       "path": ".deepsource.toml",
192:       "bytes": 106,
193:       "lines": 8
194:     },
195:     {
196:       "revision": "head",
197:       "path": ".env",
198:       "bytes": 23,
199:       "lines": 1
200:     },
201:     {
202:       "revision": "head",
203:       "path": ".github/workflows/tofarev.yml",
204:       "bytes": 1071,
205:       "lines": 25
206:     },
207:     {
208:       "revision": "head",
209:       "path": ".gitignore",
210:       "bytes": 444,
211:       "lines": 35
212:     },
213:     {
214:       "revision": "head",
215:       "path": ".gitlab-ci.yml",
216:       "bytes": 1047,
217:       "lines": 22
218:     },
219:     {
220:       "revision": "head",
221:       "path": "arista/veos/docker/Dockerfile",
222:       "bytes": 255,
223:       "lines": 9
224:     },
225:     {
226:       "revision": "head",
227:       "path": "arista/veos/docker/launch.py",
228:       "bytes": 6224,
229:       "lines": 194
230:     },
231:     {
232:       "revision": "head",
233:       "path": "arista/veos/Makefile",
234:       "bytes": 1034,
235:       "lines": 25
236:     },
237:     {
238:       "revision": "head",
239:       "path": "arista/veos/README.md",
240:       "bytes": 1281,
241:       "lines": 36
242:     },
243:     {
244:       "revision": "head",
245:       "path": "arrcus/arcos/docker/Dockerfile",
246:       "bytes": 120,
247:       "lines": 7
248:     },
249:     {
250:       "revision": "head",
251:       "path": "arrcus/arcos/docker/launch.py",
252:       "bytes": 13701,
253:       "lines": 370
254:     },
255:     {
256:       "revision": "head",
257:       "path": "arrcus/arcos/Makefile",
258:       "bytes": 286,
259:       "lines": 11
260:     },
261:     {
262:       "revision": "head",
263:       "path": "arrcus/arcos/README.md",
264:       "bytes": 1724,
265:       "lines": 61
266:     },
267:     {
268:       "revision": "head",
269:       "path": "arrcus/arcos/smoke-test.sh",
270:       "bytes": 2983,
271:       "lines": 105
272:     },
273:     {
274:       "revision": "head",
275:       "path": "aruba/aoscx/docker/Dockerfile",
276:       "bytes": 322,
277:       "lines": 14
278:     },
279:     {
280:       "revision": "head",
281:       "path": "aruba/aoscx/docker/launch.py",
282:       "bytes": 6223,
283:       "lines": 189
284:     },
285:     {
286:       "revision": "head",
287:       "path": "aruba/aoscx/Makefile",
288:       "bytes": 316,
289:       "lines": 11
290:     },
291:     {
292:       "revision": "head",
293:       "path": "aruba/aoscx/README.md",
294:       "bytes": 1031,
295:       "lines": 28
296:     },
297:     {
298:       "revision": "head",
299:       "path": "build-base-image.sh",
300:       "bytes": 300,
301:       "lines": 13
302:     },
303:     {
304:       "revision": "head",
305:       "path": "cisco/asav/docker/Dockerfile",
306:       "bytes": 80,
307:       "lines": 5
308:     },
309:     {
310:       "revision": "head",
311:       "path": "cisco/asav/docker/launch.py",
312:       "bytes": 8663,
313:       "lines": 268
314:     },
315:     {
316:       "revision": "head",
317:       "path": "cisco/asav/Makefile",
318:       "bytes": 249,
319:       "lines": 11
320:     },
321:     {
322:       "revision": "head",
323:       "path": "cisco/asav/README.md",
324:       "bytes": 2133,
325:       "lines": 68
326:     },
327:     {
328:       "revision": "head",
329:       "path": "cisco/c8000v/docker/Dockerfile",
330:       "bytes": 193,
331:       "lines": 12
332:     },
333:     {
334:       "revision": "head",
335:       "path": "cisco/c8000v/docker/launch.py",
336:       "bytes": 16574,
337:       "lines": 480
338:     },
339:     {
340:       "revision": "head",
341:       "path": "cisco/c8000v/Makefile",
342:       "bytes": 2178,
343:       "lines": 51
344:     },
345:     {
346:       "revision": "head",
347:       "path": "cisco/c8000v/README.md",
348:       "bytes": 8825,
349:       "lines": 222
350:     },
351:     {
352:       "revision": "head",
353:       "path": "cisco/cat9kv/docker/Dockerfile",
354:       "bytes": 298,
355:       "lines": 11
356:     },
357:     {
358:       "revision": "head",
359:       "path": "cisco/cat9kv/docker/launch.py",
360:       "bytes": 8036,
361:       "lines": 270
362:     },
363:     {
364:       "revision": "head",
365:       "path": "cisco/cat9kv/Makefile",
366:       "bytes": 460,
367:       "lines": 13
368:     },
369:     {
370:       "revision": "head",
371:       "path": "cisco/cat9kv/README.md",
372:       "bytes": 4101,
373:       "lines": 119
374:     },
375:     {
376:       "revision": "head",
377:       "path": "cisco/csr1000v/docker/Dockerfile",
378:       "bytes": 155,
379:       "lines": 9
380:     },
381:     {
382:       "revision": "head",
383:       "path": "cisco/csr1000v/docker/launch.py",
384:       "bytes": 8713,
385:       "lines": 314
386:     },
387:     {
388:       "revision": "head",
389:       "path": "cisco/csr1000v/Makefile",
390:       "bytes": 721,
391:       "lines": 21
392:     },
393:     {
394:       "revision": "head",
395:       "path": "cisco/csr1000v/README.md",
396:       "bytes": 3441,
397:       "lines": 78
398:     },
399:     {
400:       "revision": "head",
401:       "path": "cisco/ftdv/docker/Dockerfile",
402:       "bytes": 129,
403:       "lines": 8
404:     },
405:     {
406:       "revision": "head",
407:       "path": "cisco/ftdv/docker/launch.py",
408:       "bytes": 11036,
409:       "lines": 324
410:     },
411:     {
412:       "revision": "head",
413:       "path": "cisco/ftdv/Makefile",
414:       "bytes": 352,
415:       "lines": 12
416:     },
417:     {
418:       "revision": "head",
419:       "path": "cisco/ftdv/README.md",
420:       "bytes": 1393,
421:       "lines": 46
422:     },
423:     {
424:       "revision": "head",
425:       "path": "cisco/iol/docker/Dockerfile",
426:       "bytes": 903,
427:       "lines": 37
428:     },
429:     {
430:       "revision": "head",
431:       "path": "cisco/iol/docker/entrypoint.sh",
432:       "bytes": 90,
433:       "lines": 3
434:     },
435:     {
436:       "revision": "head",
437:       "path": "cisco/iol/Makefile",
438:       "bytes": 2312,
439:       "lines": 55
440:     },
441:     {
442:       "revision": "head",
443:       "path": "cisco/iol/README.md",
444:       "bytes": 2779,
445:       "lines": 66
446:     },
447:     {
448:       "revision": "head",
449:       "path": "cisco/n9kv/docker/Dockerfile",
450:       "bytes": 196,
451:       "lines": 10
452:     },
453:     {
454:       "revision": "head",
455:       "path": "cisco/n9kv/docker/launch.py",
456:       "bytes": 7707,
457:       "lines": 248
458:     },
459:     {
460:       "revision": "head",
461:       "path": "cisco/n9kv/Makefile",
462:       "bytes": 368,
463:       "lines": 12
464:     },
465:     {
466:       "revision": "head",
467:       "path": "cisco/n9kv/README.md",
468:       "bytes": 1251,
469:       "lines": 45
470:     },
471:     {
472:       "revision": "head",
473:       "path": "cisco/nxos/docker/Dockerfile",
474:       "bytes": 120,
475:       "lines": 7
476:     },
477:     {
478:       "revision": "head",
479:       "path": "cisco/nxos/docker/launch.py",
480:       "bytes": 5944,
481:       "lines": 203
482:     },
483:     {
484:       "revision": "head",
485:       "path": "cisco/nxos/Makefile",
486:       "bytes": 371,
487:       "lines": 13
488:     },
489:     {
490:       "revision": "head",
491:       "path": "cisco/nxos/README.md",
492:       "bytes": 1181,
493:       "lines": 37
494:     },
495:     {
496:       "revision": "head",
497:       "path": "cisco/sdwan-components/docker/Dockerfile",
498:       "bytes": 442,
499:       "lines": 22
500:     },
501:     {
502:       "revision": "head",
503:       "path": "cisco/sdwan-components/docker/launch.py",
504:       "bytes": 10580,
505:       "lines": 329
506:     },
507:     {
508:       "revision": "head",
509:       "path": "cisco/sdwan-components/docker/templates/controller-zcloud.xml.j2",
510:       "bytes": 1542,
511:       "lines": 59
512:     },
513:     {
514:       "revision": "head",
515:       "path": "cisco/sdwan-components/docker/templates/manager-zcloud.xml.j2",
516:       "bytes": 1544,
517:       "lines": 59
518:     },
519:     {
520:       "revision": "head",
521:       "path": "cisco/sdwan-components/docker/templates/validator-zcloud.xml.j2",
522:       "bytes": 1574,
523:       "lines": 62
524:     },
525:     {
526:       "revision": "head",
527:       "path": "cisco/sdwan-components/Makefile",
528:       "bytes": 2260,
529:       "lines": 44
530:     },
531:     {
532:       "revision": "head",
533:       "path": "cisco/sdwan-components/README.md",
534:       "bytes": 1908,
535:       "lines": 91
536:     },
537:     {
538:       "revision": "head",
539:       "path": "cisco/vios/docker/Dockerfile",
540:       "bytes": 116,
541:       "lines": 7
542:     },
543:     {
544:       "revision": "head",
545:       "path": "cisco/vios/docker/launch.py",
546:       "bytes": 7023,
547:       "lines": 221
548:     },
549:     {
550:       "revision": "head",
551:       "path": "cisco/vios/Makefile",
552:       "bytes": 509,
553:       "lines": 17
554:     },
555:     {
556:       "revision": "head",
557:       "path": "cisco/vios/README.md",
558:       "bytes": 4730,
559:       "lines": 143
560:     },
561:     {
562:       "revision": "head",
563:       "path": "cisco/xrd-vrouter/docker/cloud-init-disable-net.cfg",
564:       "bytes": 28,
565:       "lines": 1
566:     },
567:     {
568:       "revision": "head",
569:       "path": "cisco/xrd-vrouter/docker/Dockerfile",
570:       "bytes": 402,
571:       "lines": 11
572:     },
573:     {
574:       "revision": "head",
575:       "path": "cisco/xrd-vrouter/docker/guest-init.sh",
576:       "bytes": 5708,
577:       "lines": 122
578:     },
579:     {
580:       "revision": "head",
581:       "path": "cisco/xrd-vrouter/docker/launch.py",
582:       "bytes": 10326,
583:       "lines": 266
584:     },
585:     {
586:       "revision": "head",
587:       "path": "cisco/xrd-vrouter/docker/make-golden.sh",
588:       "bytes": 5404,
589:       "lines": 139
590:     },
591:     {
592:       "revision": "head",
593:       "path": "cisco/xrd-vrouter/docker/netplan-mgmt.yaml",
594:       "bytes": 457,
595:       "lines": 13
596:     },
597:     {
598:       "revision": "head",
599:       "path": "cisco/xrd-vrouter/docker/xrd-guest-init.service",
600:       "bytes": 261,
601:       "lines": 13
602:     },
603:     {
604:       "revision": "head",
605:       "path": "cisco/xrd-vrouter/docker/xrd-unconfined",
606:       "bytes": 274,
607:       "lines": 16
608:     },
609:     {
610:       "revision": "head",
611:       "path": "cisco/xrd-vrouter/Makefile",
612:       "bytes": 1286,
613:       "lines": 33
614:     },
615:     {
616:       "revision": "head",
617:       "path": "cisco/xrd-vrouter/README.md",
618:       "bytes": 4702,
619:       "lines": 79
620:     },
621:     {
622:       "revision": "head",
623:       "path": "cisco/xrv/docker/Dockerfile",
624:       "bytes": 126,
625:       "lines": 7
626:     },
627:     {
628:       "revision": "head",
629:       "path": "cisco/xrv/docker/launch.py",
630:       "bytes": 7862,
631:       "lines": 259
632:     },
633:     {
634:       "revision": "head",
635:       "path": "cisco/xrv/Makefile",
636:       "bytes": 910,
637:       "lines": 27
638:     },
639:     {
640:       "revision": "head",
641:       "path": "cisco/xrv/README.md",
642:       "bytes": 1498,
643:       "lines": 29
644:     },
645:     {
646:       "revision": "head",
647:       "path": "cisco/xrv9k/docker/Dockerfile",
648:       "bytes": 148,
649:       "lines": 8
650:     },
651:     {
652:       "revision": "head",
653:       "path": "cisco/xrv9k/docker/launch.py",
654:       "bytes": 13568,
655:       "lines": 426
656:     },
657:     {
658:       "revision": "head",
659:       "path": "cisco/xrv9k/LICENSE",
660:       "bytes": 1109,
661:       "lines": 21
662:     },
663:     {
664:       "revision": "head",
665:       "path": "cisco/xrv9k/Makefile",
666:       "bytes": 561,
667:       "lines": 23
668:     },
669:     {
670:       "revision": "head",
671:       "path": "cisco/xrv9k/README.md",
672:       "bytes": 2699,
673:       "lines": 63
674:     },
675:     {
676:       "revision": "head",
677:       "path": "CODE_OF_CONDUCT.md",
678:       "bytes": 95,
679:       "lines": 3
680:     },
681:     {
682:       "revision": "head",
683:       "path": "common/healthcheck.py",
684:       "bytes": 339,
685:       "lines": 18
686:     },
687:     {
688:       "revision": "head",
689:       "path": "common/vrnetlab.py",
690:       "bytes": 64326,
691:       "lines": 1716
692:     },
693:     {
694:       "revision": "head",
695:       "path": "CONTRIBUTING.md",
696:       "bytes": 709,
697:       "lines": 17
698:     },
699:     {
700:       "revision": "head",
701:       "path": "dell/dell_sonic/docker/backup.sh",
702:       "bytes": 2833,
703:       "lines": 107
704:     },
705:     {
706:       "revision": "head",
707:       "path": "dell/dell_sonic/docker/Dockerfile",
708:       "bytes": 122,
709:       "lines": 8
710:     },
711:     {
712:       "revision": "head",
713:       "path": "dell/dell_sonic/docker/launch.py",
714:       "bytes": 5835,
715:       "lines": 185
716:     },
717:     {
718:       "revision": "head",
719:       "path": "dell/dell_sonic/Makefile",
720:       "bytes": 380,
721:       "lines": 12
722:     },
723:     {
724:       "revision": "head",
725:       "path": "dell/dell_sonic/README.md",
726:       "bytes": 1030,
727:       "lines": 23
728:     },
729:     {
730:       "revision": "head",
731:       "path": "dell/ftosv/docker/Dockerfile",
732:       "bytes": 309,
733:       "lines": 10
734:     },
735:     {
736:       "revision": "head",
737:       "path": "dell/ftosv/docker/launch.py",
738:       "bytes": 8356,
739:       "lines": 230
740:     },
741:     {
742:       "revision": "head",
743:       "path": "dell/ftosv/Makefile",
744:       "bytes": 287,
745:       "lines": 11
746:     },
747:     {
748:       "revision": "head",
749:       "path": "dell/ftosv/README.md",
750:       "bytes": 17648,
751:       "lines": 235
752:     },
753:     {
754:       "revision": "head",
755:       "path": "dev-notes.md",
756:       "bytes": 352,
757:       "lines": 13
758:     },
759:     {
760:       "revision": "head",
761:       "path": "extreme/exos/docker/Dockerfile",
762:       "bytes": 80,
763:       "lines": 5
764:     },
765:     {
766:       "revision": "head",
767:       "path": "extreme/exos/docker/launch.py",
768:       "bytes": 7926,
769:       "lines": 219
770:     },
771:     {
772:       "revision": "head",
773:       "path": "extreme/exos/Makefile",
774:       "bytes": 261,
775:       "lines": 11
776:     },
777:     {
778:       "revision": "head",
779:       "path": "extreme/exos/README.md",
780:       "bytes": 1735,
781:       "lines": 42
782:     },
783:     {
784:       "revision": "head",
785:       "path": "extreme/voss/docker/Dockerfile",
786:       "bytes": 80,
787:       "lines": 5
788:     },
789:     {
790:       "revision": "head",
791:       "path": "extreme/voss/docker/launch.py",
792:       "bytes": 9114,
793:       "lines": 245
794:     },
795:     {
796:       "revision": "head",
797:       "path": "extreme/voss/Makefile",
798:       "bytes": 296,
799:       "lines": 11
800:     },
801:     {
802:       "revision": "head",
803:       "path": "extreme/voss/README.md",
804:       "bytes": 790,
805:       "lines": 27
806:     },
807:     {
808:       "revision": "head",
809:       "path": "f5_bigip/docker/Dockerfile",
810:       "bytes": 229,
811:       "lines": 13
812:     },
813:     {
814:       "revision": "head",
815:       "path": "f5_bigip/docker/launch.py",
816:       "bytes": 16156,
817:       "lines": 474
818:     },
819:     {
820:       "revision": "head",
821:       "path": "f5_bigip/Makefile",
822:       "bytes": 529,
823:       "lines": 17
824:     },
825:     {
826:       "revision": "head",
827:       "path": "f5_bigip/README.md",
828:       "bytes": 1273,
829:       "lines": 31
830:     },
831:     {
832:       "revision": "head",
833:       "path": "fortinet/common/__init__.py",
834:       "bytes": 66,
835:       "lines": 1
836:     },
837:     {
838:       "revision": "head",
839:       "path": "fortinet/common/config_diff.py",
840:       "bytes": 4069,
841:       "lines": 138
842:     },
843:     {
844:       "revision": "head",
845:       "path": "fortinet/common/env.py",
846:       "bytes": 1523,
847:       "lines": 48
848:     },
849:     {
850:       "revision": "head",
851:       "path": "fortinet/common/features/__init__.py",
852:       "bytes": 1534,
853:       "lines": 49
854:     },
855:     {
856:       "revision": "head",
857:       "path": "fortinet/common/features/capture_config.py",
858:       "bytes": 14172,
859:       "lines": 362
860:     },
861:     {
862:       "revision": "head",
863:       "path": "fortinet/common/features/default_config.py",
864:       "bytes": 1077,
865:       "lines": 33
866:     },
867:     {
868:       "revision": "head",
869:       "path": "fortinet/common/features/disks.py",
870:       "bytes": 3193,
871:       "lines": 86
872:     },
873:     {
874:       "revision": "head",
875:       "path": "fortinet/common/features/fortiguard_hooks.py",
876:       "bytes": 3440,
877:       "lines": 103
878:     },
879:     {
880:       "revision": "head",
881:       "path": "fortinet/common/features/fortitoken.py",
882:       "bytes": 2951,
883:       "lines": 95
884:     },
885:     {
886:       "revision": "head",
887:       "path": "fortinet/common/features/image_info.py",
888:       "bytes": 2616,
889:       "lines": 81
890:     },
891:     {
892:       "revision": "head",
893:       "path": "fortinet/common/features/license.py",
894:       "bytes": 10131,
895:       "lines": 268
896:     },
897:     {
898:       "revision": "head",
899:       "path": "fortinet/common/features/mgmt_dns.py",
900:       "bytes": 2139,
901:       "lines": 60
902:     },
903:     {
904:       "revision": "head",
905:       "path": "fortinet/common/features/mgmt_net.py",
906:       "bytes": 4174,
907:       "lines": 114
908:     },
909:     {
910:       "revision": "head",
911:       "path": "fortinet/common/features/product.py",
912:       "bytes": 3918,
913:       "lines": 107
914:     },
915:     {
916:       "revision": "head",
917:       "path": "fortinet/common/file_watcher.py",
918:       "bytes": 2307,
919:       "lines": 69
920:     },
921:     {
922:       "revision": "head",
923:       "path": "fortinet/common/fos_healthcheck.py",
924:       "bytes": 3984,
925:       "lines": 111
926:     },
927:     {
928:       "revision": "head",
929:       "path": "fortinet/common/host_forwarded_bridge.py",
930:       "bytes": 3614,
931:       "lines": 95
932:     },
933:     {
934:       "revision": "head",
935:       "path": "fortinet/common/net_mgmt_strategy.py",
936:       "bytes": 1299,
937:       "lines": 48
938:     },
939:     {
940:       "revision": "head",
941:       "path": "fortinet/common/passthrough_redirect.py",
942:       "bytes": 8909,
943:       "lines": 201
944:     },
945:     {
946:       "revision": "head",
947:       "path": "fortinet/common/tftp.py",
948:       "bytes": 2742,
949:       "lines": 88
950:     },
951:     {
952:       "revision": "head",
953:       "path": "fortinet/fortigate/.gitignore",
954:       "bytes": 7,
955:       "lines": 1
956:     },
957:     {
958:       "revision": "head",
959:       "path": "fortinet/fortigate/docker/Dockerfile",
960:       "bytes": 1146,
961:       "lines": 27
962:     },
963:     {
964:       "revision": "head",
965:       "path": "fortinet/fortigate/docker/launch.py",
966:       "bytes": 106,
967:       "lines": 7
968:     },
969:     {
970:       "revision": "head",
971:       "path": "fortinet/fortigate/Makefile",
972:       "bytes": 1146,
973:       "lines": 24
974:     },
975:     {
976:       "revision": "head",
977:       "path": "fortinet/fortiproxy/.gitignore",
978:       "bytes": 8,
979:       "lines": 1
980:     },
981:     {
982:       "revision": "head",
983:       "path": "fortinet/fortiproxy/docker/Dockerfile",
984:       "bytes": 418,
985:       "lines": 17
986:     },
987:     {
988:       "revision": "head",
989:       "path": "fortinet/fortiproxy/docker/launch.py",
990:       "bytes": 107,
991:       "lines": 7
992:     },
993:     {
994:       "revision": "head",
995:       "path": "fortinet/fortiproxy/docker/README.md",
996:       "bytes": 189,
997:       "lines": 4
998:     },
999:     {
1000:       "revision": "head",
1001:       "path": "fortinet/fortiproxy/Makefile",
1002:       "bytes": 1156,
1003:       "lines": 25
1004:     },
1005:     {
1006:       "revision": "head",
1007:       "path": "fortinet/fortiproxy/README.md",
1008:       "bytes": 1044,
1009:       "lines": 22
1010:     },
1011:     {
1012:       "revision": "head",
1013:       "path": "fortinet/tests/test_common_capture_pki.py",
1014:       "bytes": 12387,
1015:       "lines": 239
1016:     },
1017:     {
1018:       "revision": "head",
1019:       "path": "fortinet/tests/test_common_commander_scheduler.py",
1020:       "bytes": 9852,
1021:       "lines": 183
1022:     },
1023:     {
1024:       "revision": "head",
1025:       "path": "fortinet/tests/test_common_commands.py",
1026:       "bytes": 5500,
1027:       "lines": 137
1028:     },
1029:     {
1030:       "revision": "head",
1031:       "path": "fortinet/tests/test_common_environment_watchers.py",
1032:       "bytes": 5635,
1033:       "lines": 122
1034:     },
1035:     {
1036:       "revision": "head",
1037:       "path": "fortinet/tests/test_common_features.py",
1038:       "bytes": 17522,
1039:       "lines": 346
1040:     },
1041:     {
1042:       "revision": "head",
1043:       "path": "fortinet/tests/test_common_license.py",
1044:       "bytes": 9565,
1045:       "lines": 180
1046:     },
1047:     {
1048:       "revision": "head",
1049:       "path": "fortinet/tests/test_common_network_launch.py",
1050:       "bytes": 12810,
1051:       "lines": 239
1052:     },
1053:     {
1054:       "revision": "head",
1055:       "path": "fortinet/tests/test_fos_commander.py",
1056:       "bytes": 3608,
1057:       "lines": 93
1058:     },
1059:     {
1060:       "revision": "head",
1061:       "path": "fortinet/tests/test_vrnetlab.py",
1062:       "bytes": 4478,
1063:       "lines": 127
1064:     },
1065:     {
1066:       "revision": "head",
1067:       "path": "freebsd/docker/backup.sh",
1068:       "bytes": 2071,
1069:       "lines": 84
1070:     },
1071:     {
1072:       "revision": "head",
1073:       "path": "freebsd/docker/Dockerfile",
1074:       "bytes": 442,
1075:       "lines": 22
1076:     },
1077:     {
1078:       "revision": "head",
1079:       "path": "freebsd/docker/launch.py",
1080:       "bytes": 8117,
1081:       "lines": 257
1082:     },
1083:     {
1084:       "revision": "head",
1085:       "path": "freebsd/download.sh",
1086:       "bytes": 682,
1087:       "lines": 22
1088:     },
1089:     {
1090:       "revision": "head",
1091:       "path": "freebsd/Makefile",
1092:       "bytes": 342,
1093:       "lines": 17
1094:     },
1095:     {
1096:       "revision": "head",
1097:       "path": "freebsd/README.md",
1098:       "bytes": 1714,
1099:       "lines": 52
1100:     },
1101:     {
1102:       "revision": "head",
1103:       "path": "hp/vsr1000/docker/Dockerfile",
1104:       "bytes": 187,
1105:       "lines": 8
1106:     },
1107:     {
1108:       "revision": "head",
1109:       "path": "hp/vsr1000/docker/launch.py",
1110:       "bytes": 5525,
1111:       "lines": 160
1112:     },
1113:     {
1114:       "revision": "head",
1115:       "path": "hp/vsr1000/Makefile",
1116:       "bytes": 342,
1117:       "lines": 13
1118:     },
1119:     {
1120:       "revision": "head",
1121:       "path": "hp/vsr1000/README.md",
1122:       "bytes": 1049,
1123:       "lines": 34
1124:     },
1125:     {
1126:       "revision": "head",
1127:       "path": "huawei/huawei_vrp/docker/Dockerfile",
1128:       "bytes": 133,
1129:       "lines": 7
1130:     },
1131:     {
1132:       "revision": "head",
1133:       "path": "huawei/huawei_vrp/docker/launch.py",
1134:       "bytes": 18313,
1135:       "lines": 468
1136:     },
1137:     {
1138:       "revision": "head",
1139:       "path": "huawei/huawei_vrp/Makefile",
1140:       "bytes": 334,
1141:       "lines": 12
1142:     },
1143:     {
1144:       "revision": "head",
1145:       "path": "huawei/huawei_vrp/README.md",
1146:       "bytes": 426,
1147:       "lines": 27
1148:     },
1149:     {
1150:       "revision": "head",
1151:       "path": "ipinfusion/ocnos/docker/Dockerfile",
1152:       "bytes": 127,
1153:       "lines": 7
1154:     },
1155:     {
1156:       "revision": "head",
1157:       "path": "ipinfusion/ocnos/docker/launch.py",
1158:       "bytes": 7658,
1159:       "lines": 223
1160:     },
1161:     {
1162:       "revision": "head",
1163:       "path": "ipinfusion/ocnos/Makefile",
1164:       "bytes": 522,
1165:       "lines": 16
1166:     },
1167:     {
1168:       "revision": "head",
1169:       "path": "ipinfusion/ocnos/README.md",
1170:       "bytes": 1417,
1171:       "lines": 49
1172:     },
1173:     {
1174:       "revision": "head",
1175:       "path": "juniper/apstra/docker/Dockerfile",
1176:       "bytes": 369,
1177:       "lines": 14
1178:     },
1179:     {
1180:       "revision": "head",
1181:       "path": "juniper/apstra/docker/launch.py",
1182:       "bytes": 10481,
1183:       "lines": 262
1184:     },
1185:     {
1186:       "revision": "head",
1187:       "path": "juniper/apstra/Makefile",
1188:       "bytes": 1225,
1189:       "lines": 36
1190:     },
1191:     {
1192:       "revision": "head",
1193:       "path": "juniper/apstra/README.md",
1194:       "bytes": 10010,
1195:       "lines": 307
1196:     },
1197:     {
1198:       "revision": "head",
1199:       "path": "juniper/vjunosevolved/docker/Dockerfile",
1200:       "bytes": 325,
1201:       "lines": 14
1202:     },
1203:     {
1204:       "revision": "head",
1205:       "path": "juniper/vjunosevolved/docker/init.conf",
1206:       "bytes": 855,
1207:       "lines": 44
1208:     },
1209:     {
1210:       "revision": "head",
1211:       "path": "juniper/vjunosevolved/docker/launch.py",
1212:       "bytes": 8866,
1213:       "lines": 246
1214:     },
1215:     {
1216:       "revision": "head",
1217:       "path": "juniper/vjunosevolved/docker/make-config.sh",
1218:       "bytes": 1402,
1219:       "lines": 60
1220:     },
1221:     {
1222:       "revision": "head",
1223:       "path": "juniper/vjunosevolved/Makefile",
1224:       "bytes": 352,
1225:       "lines": 15
1226:     },
1227:     {
1228:       "revision": "head",
1229:       "path": "juniper/vjunosevolved/README.md",
1230:       "bytes": 718,
1231:       "lines": 19
1232:     },
1233:     {
1234:       "revision": "head",
1235:       "path": "juniper/vjunosrouter/docker/Dockerfile",
1236:       "bytes": 325,
1237:       "lines": 14
1238:     },
1239:     {
1240:       "revision": "head",
1241:       "path": "juniper/vjunosrouter/docker/init.conf",
1242:       "bytes": 915,
1243:       "lines": 51
1244:     },
1245:     {
1246:       "revision": "head",
1247:       "path": "juniper/vjunosrouter/docker/launch.py",
1248:       "bytes": 7341,
1249:       "lines": 212
1250:     },
1251:     {
1252:       "revision": "head",
1253:       "path": "juniper/vjunosrouter/docker/make-config.sh",
1254:       "bytes": 1402,
1255:       "lines": 60
1256:     },
1257:     {
1258:       "revision": "head",
1259:       "path": "juniper/vjunosrouter/Makefile",
1260:       "bytes": 824,
1261:       "lines": 31
1262:     },
1263:     {
1264:       "revision": "head",
1265:       "path": "juniper/vjunosrouter/README.md",
1266:       "bytes": 494,
1267:       "lines": 15
1268:     },
1269:     {
1270:       "revision": "head",
1271:       "path": "juniper/vjunosswitch/docker/Dockerfile",
1272:       "bytes": 325,
1273:       "lines": 14
1274:     },
1275:     {
1276:       "revision": "head",
1277:       "path": "juniper/vjunosswitch/docker/init.conf",
1278:       "bytes": 915,
1279:       "lines": 51
1280:     },
1281:     {
1282:       "revision": "head",
1283:       "path": "juniper/vjunosswitch/docker/launch.py",
1284:       "bytes": 7358,
1285:       "lines": 212
1286:     },
1287:     {
1288:       "revision": "head",
1289:       "path": "juniper/vjunosswitch/docker/make-config.sh",
1290:       "bytes": 1402,
1291:       "lines": 60
1292:     },
1293:     {
1294:       "revision": "head",
1295:       "path": "juniper/vjunosswitch/Makefile",
1296:       "bytes": 886,
1297:       "lines": 34
1298:     },
1299:     {
1300:       "revision": "head",
1301:       "path": "juniper/vjunosswitch/README.md",
1302:       "bytes": 513,
1303:       "lines": 17
1304:     },
1305:     {
1306:       "revision": "head",
1307:       "path": "juniper/vmx/docker/Dockerfile",
1308:       "bytes": 295,
1309:       "lines": 12
1310:     },
1311:     {
1312:       "revision": "head",
1313:       "path": "juniper/vmx/docker/launch.py",
1314:       "bytes": 17750,
1315:       "lines": 496
1316:     },
1317:     {
1318:       "revision": "head",
1319:       "path": "juniper/vmx/Makefile",
1320:       "bytes": 590,
1321:       "lines": 22
1322:     },
1323:     {
1324:       "revision": "head",
1325:       "path": "juniper/vmx/README.md",
1326:       "bytes": 1880,
1327:       "lines": 45
1328:     },
1329:     {
1330:       "revision": "head",
1331:       "path": "juniper/vmx/vmx-extract.sh",
1332:       "bytes": 894,
1333:       "lines": 24
1334:     },
1335:     {
1336:       "revision": "head",
1337:       "path": "juniper/vqfx/docker/Dockerfile",
1338:       "bytes": 328,
1339:       "lines": 18
1340:     },
1341:     {
1342:       "revision": "head",
1343:       "path": "juniper/vqfx/docker/launch.py",
1344:       "bytes": 10990,
1345:       "lines": 305
1346:     },
1347:     {
1348:       "revision": "head",
1349:       "path": "juniper/vqfx/Makefile",
1350:       "bytes": 2052,
1351:       "lines": 35
1352:     },
1353:     {
1354:       "revision": "head",
1355:       "path": "juniper/vqfx/README.md",
1356:       "bytes": 161,
1357:       "lines": 6
1358:     },
1359:     {
1360:       "revision": "head",
1361:       "path": "juniper/vsrx/docker/Dockerfile",
1362:       "bytes": 240,
1363:       "lines": 11
1364:     },
1365:     {
1366:       "revision": "head",
1367:       "path": "juniper/vsrx/docker/init.conf",
1368:       "bytes": 848,
1369:       "lines": 43
1370:     },
1371:     {
1372:       "revision": "head",
1373:       "path": "juniper/vsrx/docker/launch.py",
1374:       "bytes": 6670,
1375:       "lines": 193
1376:     },
1377:     {
1378:       "revision": "head",
1379:       "path": "juniper/vsrx/docker/make-config-iso.sh",
1380:       "bytes": 416,
1381:       "lines": 24
1382:     },
1383:     {
1384:       "revision": "head",
1385:       "path": "juniper/vsrx/Makefile",
1386:       "bytes": 303,
1387:       "lines": 12
1388:     },
1389:     {
1390:       "revision": "head",
1391:       "path": "juniper/vsrx/README.md",
1392:       "bytes": 1416,
1393:       "lines": 29
1394:     },
1395:     {
1396:       "revision": "head",
1397:       "path": "LICENSE",
1398:       "bytes": 1109,
1399:       "lines": 21
1400:     },
1401:     {
1402:       "revision": "head",
1403:       "path": "makefile-install.include",
1404:       "bytes": 3279,
1405:       "lines": 48
1406:     },
1407:     {
1408:       "revision": "head",
1409:       "path": "makefile-sanity.include",
1410:       "bytes": 370,
1411:       "lines": 8
1412:     },
1413:     {
1414:       "revision": "head",
1415:       "path": "makefile.include",
1416:       "bytes": 3274,
1417:       "lines": 85
1418:     },
1419:     {
1420:       "revision": "head",
1421:       "path": "mikrotik/routeros/docker/Dockerfile",
1422:       "bytes": 350,
1423:       "lines": 15
1424:     },
1425:     {
1426:       "revision": "head",
1427:       "path": "mikrotik/routeros/docker/launch.py",
1428:       "bytes": 11967,
1429:       "lines": 313
1430:     },
1431:     {
1432:       "revision": "head",
1433:       "path": "mikrotik/routeros/Makefile",
1434:       "bytes": 1687,
1435:       "lines": 39
1436:     },
1437:     {
1438:       "revision": "head",
1439:       "path": "mikrotik/routeros/README.md",
1440:       "bytes": 998,
1441:       "lines": 35
1442:     },
1443:     {
1444:       "revision": "head",
1445:       "path": "netapp/ontap/docker/Dockerfile",
1446:       "bytes": 724,
1447:       "lines": 26
1448:     },
1449:     {
1450:       "revision": "head",
1451:       "path": "netapp/ontap/docker/launch.py",
1452:       "bytes": 22293,
1453:       "lines": 521
1454:     },
1455:     {
1456:       "revision": "head",
1457:       "path": "netapp/ontap/Makefile",
1458:       "bytes": 337,
1459:       "lines": 12
1460:     },
1461:     {
1462:       "revision": "head",
1463:       "path": "netapp/ontap/README.md",
1464:       "bytes": 7014,
1465:       "lines": 171
1466:     },
1467:     {
1468:       "revision": "head",
1469:       "path": "nokia/cmglinux/docker/Dockerfile",
1470:       "bytes": 412,
1471:       "lines": 21
1472:     },
1473:     {
1474:       "revision": "head",
1475:       "path": "nokia/cmglinux/docker/launch.py",
1476:       "bytes": 9068,
1477:       "lines": 299
1478:     },
1479:     {
1480:       "revision": "head",
1481:       "path": "nokia/cmglinux/Makefile",
1482:       "bytes": 304,
1483:       "lines": 12
1484:     },
1485:     {
1486:       "revision": "head",
1487:       "path": "nokia/cmglinux/README.md",
1488:       "bytes": 2931,
1489:       "lines": 100
1490:     },
1491:     {
1492:       "revision": "head",
1493:       "path": "nokia/sros/docker/Dockerfile",
1494:       "bytes": 152,
1495:       "lines": 6
1496:     },
1497:     {
1498:       "revision": "head",
1499:       "path": "nokia/sros/docker/launch.py",
1500:       "bytes": 72283,
1501:       "lines": 1983
1502:     },
1503:     {
1504:       "revision": "head",
1505:       "path": "nokia/sros/Makefile",
1506:       "bytes": 337,
1507:       "lines": 13
1508:     },
1509:     {
1510:       "revision": "head",
1511:       "path": "nokia/sros/README.md",
1512:       "bytes": 7221,
1513:       "lines": 126
1514:     },
1515:     {
1516:       "revision": "head",
1517:       "path": "nvidia/cumulus-vx/docker/Dockerfile",
1518:       "bytes": 375,
1519:       "lines": 14
1520:     },
1521:     {
1522:       "revision": "head",
1523:       "path": "nvidia/cumulus-vx/docker/launch.py",
1524:       "bytes": 24943,
1525:       "lines": 649
1526:     },
1527:     {
1528:       "revision": "head",
1529:       "path": "nvidia/cumulus-vx/Makefile",
1530:       "bytes": 1250,
1531:       "lines": 35
1532:     },
1533:     {
1534:       "revision": "head",
1535:       "path": "nvidia/cumulus-vx/README.md",
1536:       "bytes": 2977,
1537:       "lines": 101
1538:     },
1539:     {
1540:       "revision": "head",
1541:       "path": "openbsd/docker/backup.sh",
1542:       "bytes": 2069,
1543:       "lines": 84
1544:     },
1545:     {
1546:       "revision": "head",
1547:       "path": "openbsd/docker/Dockerfile",
1548:       "bytes": 428,
1549:       "lines": 20
1550:     },
1551:     {
1552:       "revision": "head",
1553:       "path": "openbsd/docker/launch.py",
1554:       "bytes": 6854,
1555:       "lines": 218
1556:     },
1557:     {
1558:       "revision": "head",
1559:       "path": "openbsd/download.sh",
1560:       "bytes": 769,
1561:       "lines": 28
1562:     },
1563:     {
1564:       "revision": "head",
1565:       "path": "openbsd/Makefile",
1566:       "bytes": 352,
1567:       "lines": 17
1568:     },
1569:     {
1570:       "revision": "head",
1571:       "path": "openbsd/README.md",
1572:       "bytes": 1769,
1573:       "lines": 52
1574:     },
1575:     {
1576:       "revision": "head",
1577:       "path": "openwrt/docker/Dockerfile",
1578:       "bytes": 152,
1579:       "lines": 9
1580:     },
1581:     {
1582:       "revision": "head",
1583:       "path": "openwrt/docker/launch.py",
1584:       "bytes": 49519,
1585:       "lines": 1288
1586:     },
1587:     {
1588:       "revision": "head",
1589:       "path": "openwrt/download.py",
1590:       "bytes": 2920,
1591:       "lines": 82
1592:     },
1593:     {
1594:       "revision": "head",
1595:       "path": "openwrt/Makefile",
1596:       "bytes": 533,
1597:       "lines": 20
1598:     },
1599:     {
1600:       "revision": "head",
1601:       "path": "openwrt/README.md",
1602:       "bytes": 5302,
1603:       "lines": 144
1604:     },
1605:     {
1606:       "revision": "head",
1607:       "path": "opnsense/docker/Dockerfile",
1608:       "bytes": 401,
1609:       "lines": 19
1610:     },
1611:     {
1612:       "revision": "head",
1613:       "path": "opnsense/docker/launch.py",
1614:       "bytes": 10379,
1615:       "lines": 280
1616:     },
1617:     {
1618:       "revision": "head",
1619:       "path": "opnsense/Makefile",
1620:       "bytes": 551,
1621:       "lines": 18
1622:     },
1623:     {
1624:       "revision": "head",
1625:       "path": "opnsense/README.md",
1626:       "bytes": 2391,
1627:       "lines": 70
1628:     },
1629:     {
1630:       "revision": "head",
1631:       "path": "paloalto/pan/docker/Dockerfile",
1632:       "bytes": 174,
1633:       "lines": 9
1634:     },
1635:     {
1636:       "revision": "head",
1637:       "path": "paloalto/pan/docker/launch.py",
1638:       "bytes": 13856,
1639:       "lines": 352
1640:     },
1641:     {
1642:       "revision": "head",
1643:       "path": "paloalto/pan/Makefile",
1644:       "bytes": 288,
1645:       "lines": 12
1646:     },
1647:     {
1648:       "revision": "head",
1649:       "path": "paloalto/pan/README.md",
1650:       "bytes": 710,
1651:       "lines": 27
1652:     },
1653:     {
1654:       "revision": "head",
1655:       "path": "plvision/plvision_sonic/docker/backup.sh",
1656:       "bytes": 2833,
1657:       "lines": 107
1658:     },
1659:     {
1660:       "revision": "head",
1661:       "path": "plvision/plvision_sonic/docker/Dockerfile",
1662:       "bytes": 503,
1663:       "lines": 17
1664:     },
1665:     {
1666:       "revision": "head",
1667:       "path": "plvision/plvision_sonic/docker/launch.py",
1668:       "bytes": 6323,
1669:       "lines": 189
1670:     },
1671:     {
1672:       "revision": "head",
1673:       "path": "plvision/plvision_sonic/Makefile",
1674:       "bytes": 458,
1675:       "lines": 13
1676:     },
1677:     {
1678:       "revision": "head",
1679:       "path": "plvision/plvision_sonic/README.md",
1680:       "bytes": 1506,
1681:       "lines": 35
1682:     },
1683:     {
1684:       "revision": "head",
1685:       "path": "pyproject.toml",
1686:       "bytes": 417,
1687:       "lines": 17
1688:     },
1689:     {
1690:       "revision": "head",
1691:       "path": "README.md",
1692:       "bytes": 8444,
1693:       "lines": 169
1694:     },
1695:     {
1696:       "revision": "head",
1697:       "path": "sonic/docker/backup.sh",
1698:       "bytes": 2833,
1699:       "lines": 107
1700:     },
1701:     {
1702:       "revision": "head",
1703:       "path": "sonic/docker/Dockerfile",
1704:       "bytes": 415,
1705:       "lines": 15
1706:     },
1707:     {
1708:       "revision": "head",
1709:       "path": "sonic/docker/launch.py",
1710:       "bytes": 6278,
1711:       "lines": 189
1712:     },
1713:     {
1714:       "revision": "head",
1715:       "path": "sonic/Makefile",
1716:       "bytes": 269,
1717:       "lines": 12
1718:     },
1719:     {
1720:       "revision": "head",
1721:       "path": "sonic/README.md",
1722:       "bytes": 1305,
1723:       "lines": 31
1724:     },
1725:     {
1726:       "revision": "head",
1727:       "path": "spirent/vstc/docker/Dockerfile",
1728:       "bytes": 115,
1729:       "lines": 7
1730:     },
1731:     {
1732:       "revision": "head",
1733:       "path": "spirent/vstc/docker/launch.py",
1734:       "bytes": 4180,
1735:       "lines": 155
1736:     },
1737:     {
1738:       "revision": "head",
1739:       "path": "spirent/vstc/Makefile",
1740:       "bytes": 211,
1741:       "lines": 9
1742:     },
1743:     {
1744:       "revision": "head",
1745:       "path": "spirent/vstc/README.md",
1746:       "bytes": 950,
1747:       "lines": 33
1748:     },
1749:     {
1750:       "revision": "head",
1751:       "path": "truenas/truenas/docker/Dockerfile",
1752:       "bytes": 294,
1753:       "lines": 11
1754:     },
1755:     {
1756:       "revision": "head",
1757:       "path": "truenas/truenas/docker/launch.py",
1758:       "bytes": 21099,
1759:       "lines": 487
1760:     },
1761:     {
1762:       "revision": "head",
1763:       "path": "truenas/truenas/docker/tnrpc.py",
1764:       "bytes": 5570,
1765:       "lines": 151
1766:     },
1767:     {
1768:       "revision": "head",
1769:       "path": "truenas/truenas/Makefile",
1770:       "bytes": 947,
1771:       "lines": 26
1772:     },
1773:     {
1774:       "revision": "head",
1775:       "path": "truenas/truenas/README.md",
1776:       "bytes": 5227,
1777:       "lines": 119
1778:     },
1779:     {
1780:       "revision": "head",
1781:       "path": "ubuntu/docker/Dockerfile",
1782:       "bytes": 412,
1783:       "lines": 21
1784:     },
1785:     {
1786:       "revision": "head",
1787:       "path": "ubuntu/docker/launch.py",
1788:       "bytes": 6754,
1789:       "lines": 216
1790:     },
1791:     {
1792:       "revision": "head",
1793:       "path": "ubuntu/download.sh",
1794:       "bytes": 512,
1795:       "lines": 18
1796:     },
1797:     {
1798:       "revision": "head",
1799:       "path": "ubuntu/Makefile",
1800:       "bytes": 332,
1801:       "lines": 18
1802:     },
1803:     {
1804:       "revision": "head",
1805:       "path": "ubuntu/README.md",
1806:       "bytes": 663,
1807:       "lines": 21
1808:     },
1809:     {
1810:       "revision": "head",
1811:       "path": "uv.lock",
1812:       "bytes": 6571,
1813:       "lines": 95
1814:     },
1815:     {
1816:       "revision": "head",
1817:       "path": "vrnetlab-base.dockerfile",
1818:       "bytes": 882,
1819:       "lines": 41
1820:     },
1821:     {
1822:       "revision": "base",
1823:       "path": "fortinet/common/cli_commands.py",
1824:       "bytes": 5602,
1825:       "lines": 185
1826:     },
1827:     {
1828:       "revision": "base",
1829:       "path": "fortinet/common/common.py",
1830:       "bytes": 3506,
1831:       "lines": 87
1832:     },
1833:     {
1834:       "revision": "base",
1835:       "path": "fortinet/common/features/base.py",
1836:       "bytes": 3138,
1837:       "lines": 115
1838:     },
1839:     {
1840:       "revision": "base",
1841:       "path": "fortinet/common/features/credentials.py",
1842:       "bytes": 2752,
1843:       "lines": 64
1844:     },
1845:     {
1846:       "revision": "base",
1847:       "path": "fortinet/common/features/pki.py",
1848:       "bytes": 17545,
1849:       "lines": 470
1850:     },
1851:     {
1852:       "revision": "base",
1853:       "path": "fortinet/common/features/startup_config.py",
1854:       "bytes": 2989,
1855:       "lines": 80
1856:     },
1857:     {
1858:       "revision": "base",
1859:       "path": "fortinet/common/fos_cli_driver.py",
1860:       "bytes": 12828,
1861:       "lines": 319
1862:     },
1863:     {
1864:       "revision": "base",
1865:       "path": "fortinet/common/fos_commander.py",
1866:       "bytes": 20149,
1867:       "lines": 511
1868:     },
1869:     {
1870:       "revision": "base",
1871:       "path": "fortinet/common/launch.py",
1872:       "bytes": 18364,
1873:       "lines": 503
1874:     },
1875:     {
1876:       "revision": "base",
1877:       "path": "fortinet/common/terminal.py",
1878:       "bytes": 12545,
1879:       "lines": 382
1880:     },
1881:     {
1882:       "revision": "base",
1883:       "path": "fortinet/fortigate/docker/README.md",
1884:       "bytes": 22149,
1885:       "lines": 469
1886:     },
1887:     {
1888:       "revision": "base",
1889:       "path": "fortinet/fortigate/README.md",
1890:       "bytes": 24956,
1891:       "lines": 493
1892:     },
1893:     {
1894:       "revision": "base",
1895:       "path": "fortinet/tests/test_common_stack_boundaries.py",
1896:       "bytes": 15060,
1897:       "lines": 343
1898:     },
1899:     {
1900:       "revision": "base",
1901:       "path": "fortinet/tests/test_common_stack_parsing.py",
1902:       "bytes": 7182,
1903:       "lines": 191
1904:     },
1905:     {
1906:       "revision": "base",
1907:       "path": "fortinet/tests/test_common_terminal_driver.py",
1908:       "bytes": 10230,
1909:       "lines": 226
1910:     },
1911:     {
1912:       "revision": "base",
1913:       "path": ".deepsource.toml",
1914:       "bytes": 106,
1915:       "lines": 8
1916:     },
1917:     {
1918:       "revision": "base",
1919:       "path": ".env",
1920:       "bytes": 23,
1921:       "lines": 1
1922:     },
1923:     {
1924:       "revision": "base",
1925:       "path": ".github/workflows/tofarev.yml",
1926:       "bytes": 1071,
1927:       "lines": 25
1928:     },
1929:     {
1930:       "revision": "base",
1931:       "path": ".gitignore",
1932:       "bytes": 444,
1933:       "lines": 35
1934:     },
1935:     {
1936:       "revision": "base",
1937:       "path": ".gitlab-ci.yml",
1938:       "bytes": 1047,
1939:       "lines": 22
1940:     },
1941:     {
1942:       "revision": "base",
1943:       "path": "arista/veos/docker/Dockerfile",
1944:       "bytes": 255,
1945:       "lines": 9
1946:     },
1947:     {
1948:       "revision": "base",
1949:       "path": "arista/veos/docker/launch.py",
1950:       "bytes": 6224,
1951:       "lines": 194
1952:     },
1953:     {
1954:       "revision": "base",
1955:       "path": "arista/veos/Makefile",
1956:       "bytes": 1034,
1957:       "lines": 25
1958:     },
1959:     {
1960:       "revision": "base",
1961:       "path": "arista/veos/README.md",
1962:       "bytes": 1281,
1963:       "lines": 36
1964:     },
1965:     {
1966:       "revision": "base",
1967:       "path": "arrcus/arcos/docker/Dockerfile",
1968:       "bytes": 120,
1969:       "lines": 7
1970:     },
1971:     {
1972:       "revision": "base",
1973:       "path": "arrcus/arcos/docker/launch.py",
1974:       "bytes": 13701,
1975:       "lines": 370
1976:     },
1977:     {
1978:       "revision": "base",
1979:       "path": "arrcus/arcos/Makefile",
1980:       "bytes": 286,
1981:       "lines": 11
1982:     },
1983:     {
1984:       "revision": "base",
1985:       "path": "arrcus/arcos/README.md",
1986:       "bytes": 1724,
1987:       "lines": 61
1988:     },
1989:     {
1990:       "revision": "base",
1991:       "path": "arrcus/arcos/smoke-test.sh",
1992:       "bytes": 2983,
1993:       "lines": 105
1994:     },
1995:     {
1996:       "revision": "base",
1997:       "path": "aruba/aoscx/docker/Dockerfile",
1998:       "bytes": 322,
1999:       "lines": 14
2000:     },

(Showing lines 1-2000 of 3553. Use offset=2001 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d11b9b001XNIcbsUQS5c4jp",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d114bf001b7PRnRynOkPtjP",
  "callID": "call_a0c6ff79436d4fd49441420c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/manifest.json"
    },
    "output": "<path>/source/manifest.json</path>\n<type>file</type>\n<content>\n1: {\n2:   \"version\": 1,\n3:   \"head\": \"1c29a33a37619b7547248e3b845130ba1f5f8ad0\",\n4:   \"base\": \"11dd16f88e2e5990de1061be498577af6c5d3552\",\n5:   \"mergeBase\": \"11dd16f88e2e5990de1061be498577af6c5d3552\",\n6:   \"changed\": [\n7:     {\n8:       \"status\": \"M\",\n9:       \"path\": \"fortinet/common/cli_commands.py\"\n10:     },\n11:     {\n12:       \"status\": \"M\",\n13:       \"path\": \"fortinet/common/common.py\"\n14:     },\n15:     {\n16:       \"status\": \"M\",\n17:       \"path\": \"fortinet/common/features/base.py\"\n18:     },\n19:     {\n20:       \"status\": \"M\",\n21:       \"path\": \"fortinet/common/features/credentials.py\"\n22:     },\n23:     {\n24:       \"status\": \"M\",\n25:       \"path\": \"fortinet/common/features/pki.py\"\n26:     },\n27:     {\n28:       \"status\": \"M\",\n29:       \"path\": \"fortinet/common/features/startup_config.py\"\n30:     },\n31:     {\n32:       \"status\": \"M\",\n33:       \"path\": \"fortinet/common/fos_cli_driver.py\"\n34:     },\n35:     {\n36:       \"status\": \"M\",\n37:       \"path\": \"fortinet/common/fos_commander.py\"\n38:     },\n39:     {\n40:       \"status\": \"M\",\n41:       \"path\": \"fortinet/common/launch.py\"\n42:     },\n43:     {\n44:       \"status\": \"M\",\n45:       \"path\": \"fortinet/common/terminal.py\"\n46:     },\n47:     {\n48:       \"status\": \"M\",\n49:       \"path\": \"fortinet/fortigate/README.md\"\n50:     },\n51:     {\n52:       \"status\": \"M\",\n53:       \"path\": \"fortinet/fortigate/docker/README.md\"\n54:     },\n55:     {\n56:       \"status\": \"A\",\n57:       \"path\": \"fortinet/tests/test_common_admin_credentials.py\"\n58:     },\n59:     {\n60:       \"status\": \"A\",\n61:       \"path\": \"fortinet/tests/test_common_recovery.py\"\n62:     },\n63:     {\n64:       \"status\": \"A\",\n65:       \"path\": \"fortinet/tests/test_common_scope_errors.py\"\n66:     },\n67:     {\n68:       \"status\": \"M\",\n69:       \"path\": \"fortinet/tests/test_common_stack_boundaries.py\"\n70:     },\n71:     {\n72:       \"status\": \"M\",\n73:       \"path\": \"fortinet/tests/test_common_stack_parsing.py\"\n74:     },\n75:     {\n76:       \"status\": \"M\",\n77:       \"path\": \"fortinet/tests/test_common_terminal_driver.py\"\n78:     }\n79:   ],\n80:   \"files\": [\n81:     {\n82:       \"revision\": \"head\",\n83:       \"path\": \"fortinet/common/cli_commands.py\",\n84:       \"bytes\": 6467,\n85:       \"lines\": 207\n86:     },\n87:     {\n88:       \"revision\": \"head\",\n89:       \"path\": \"fortinet/common/common.py\",\n90:       \"bytes\": 3700,\n91:       \"lines\": 92\n92:     },\n93:     {\n94:       \"revision\": \"head\",\n95:       \"path\": \"fortinet/common/features/base.py\",\n96:       \"bytes\": 3298,\n97:       \"lines\": 119\n98:     },\n99:     {\n100:       \"revision\": \"head\",\n101:       \"path\": \"fortinet/common/features/credentials.py\",\n102:       \"bytes\": 4094,\n103:       \"lines\": 90\n104:     },\n105:     {\n106:       \"revision\": \"head\",\n107:       \"path\": \"fortinet/common/features/pki.py\",\n108:       \"bytes\": 17660,\n109:       \"lines\": 471\n110:     },\n111:     {\n112:       \"revision\": \"head\",\n113:       \"path\": \"fortinet/common/features/startup_config.py\",\n114:       \"bytes\": 4247,\n115:       \"lines\": 117\n116:     },\n117:     {\n118:       \"revision\": \"head\",\n119:       \"path\": \"fortinet/common/fos_cli_driver.py\",\n120:       \"bytes\": 13311,\n121:       \"lines\": 331\n122:     },\n123:     {\n124:       \"revision\": \"head\",\n125:       \"path\": \"fortinet/common/fos_commander.py\",\n126:       \"bytes\": 27921,\n127:       \"lines\": 687\n128:     },\n129:     {\n130:       \"revision\": \"head\",\n131:       \"path\": \"fortinet/common/launch.py\",\n132:       \"bytes\": 18457,\n133:       \"lines\": 506\n134:     },\n135:     {\n136:       \"revision\": \"head\",\n137:       \"path\": \"fortinet/common/terminal.py\",\n138:       \"bytes\": 13228,\n139:       \"lines\": 398\n140:     },\n141:     {\n142:       \"revision\": \"head\",\n143:       \"path\": \"fortinet/fortigate/docker/README.md\",\n144:       \"bytes\": 24337,\n145:       \"lines\": 500\n146:     },\n147:     {\n148:       \"revision\": \"head\",\n149:       \"path\": \"fortinet/fortigate/README.md\",\n150:       \"bytes\": 25304,\n151:       \"lines\": 497\n152:     },\n153:     {\n154:       \"revision\": \"head\",\n155:       \"path\": \"fortinet/tests/test_common_admin_credentials.py\",\n156:       \"bytes\": 6689,\n157:       \"lines\": 154\n158:     },\n159:     {\n160:       \"revision\": \"head\",\n161:       \"path\": \"fortinet/tests/test_common_recovery.py\",\n162:       \"bytes\": 13626,\n163:       \"lines\": 292\n164:     },\n165:     {\n166:       \"revision\": \"head\",\n167:       \"path\": \"fortinet/tests/test_common_scope_errors.py\",\n168:       \"bytes\": 7676,\n169:       \"lines\": 154\n170:     },\n171:     {\n172:       \"revision\": \"head\",\n173:       \"path\": \"fortinet/tests/test_common_stack_boundaries.py\",\n174:       \"bytes\": 15421,\n175:       \"lines\": 349\n176:     },\n177:     {\n178:       \"revision\": \"head\",\n179:       \"path\": \"fortinet/tests/test_common_stack_parsing.py\",\n180:       \"bytes\": 10427,\n181:       \"lines\": 268\n182:     },\n183:     {\n184:       \"revision\": \"head\",\n185:       \"path\": \"fortinet/tests/test_common_terminal_driver.py\",\n186:       \"bytes\": 15190,\n187:       \"lines\": 332\n188:     },\n189:     {\n190:       \"revision\": \"head\",\n191:       \"path\": \".deepsource.toml\",\n192:       \"bytes\": 106,\n193:       \"lines\": 8\n194:     },\n195:     {\n196:       \"revision\": \"head\",\n197:       \"path\": \".env\",\n198:       \"bytes\": 23,\n199:       \"lines\": 1\n200:     },\n201:     {\n202:       \"revision\": \"head\",\n203:       \"path\": \".github/workflows/tofarev.yml\",\n204:       \"bytes\": 1071,\n205:       \"lines\": 25\n206:     },\n207:     {\n208:       \"revision\": \"head\",\n209:       \"path\": \".gitignore\",\n210:       \"bytes\": 444,\n211:       \"lines\": 35\n212:     },\n213:     {\n214:       \"revision\": \"head\",\n215:       \"path\": \".gitlab-ci.yml\",\n216:       \"bytes\": 1047,\n217:       \"lines\": 22\n218:     },\n219:     {\n220:       \"revision\": \"head\",\n221:       \"path\": \"arista/veos/docker/Dockerfile\",\n222:       \"bytes\": 255,\n223:       \"lines\": 9\n224:     },\n225:     {\n226:       \"revision\": \"head\",\n227:       \"path\": \"arista/veos/docker/launch.py\",\n228:       \"bytes\": 6224,\n229:       \"lines\": 194\n230:     },\n231:     {\n232:       \"revision\": \"head\",\n233:       \"path\": \"arista/veos/Makefile\",\n234:       \"bytes\": 1034,\n235:       \"lines\": 25\n236:     },\n237:     {\n238:       \"revision\": \"head\",\n239:       \"path\": \"arista/veos/README.md\",\n240:       \"bytes\": 1281,\n241:       \"lines\": 36\n242:     },\n243:     {\n244:       \"revision\": \"head\",\n245:       \"path\": \"arrcus/arcos/docker/Dockerfile\",\n246:       \"bytes\": 120,\n247:       \"lines\": 7\n248:     },\n249:     {\n250:       \"revision\": \"head\",\n251:       \"path\": \"arrcus/arcos/docker/launch.py\",\n252:       \"bytes\": 13701,\n253:       \"lines\": 370\n254:     },\n255:     {\n256:       \"revision\": \"head\",\n257:       \"path\": \"arrcus/arcos/Makefile\",\n258:       \"bytes\": 286,\n259:       \"lines\": 11\n260:     },\n261:     {\n262:       \"revision\": \"head\",\n263:       \"path\": \"arrcus/arcos/README.md\",\n264:       \"bytes\": 1724,\n265:       \"lines\": 61\n266:     },\n267:     {\n268:       \"revision\": \"head\",\n269:       \"path\": \"arrcus/arcos/smoke-test.sh\",\n270:       \"bytes\": 2983,\n271:       \"lines\": 105\n272:     },\n273:     {\n274:       \"revision\": \"head\",\n275:       \"path\": \"aruba/aoscx/docker/Dockerfile\",\n276:       \"bytes\": 322,\n277:       \"lines\": 14\n278:     },\n279:     {\n280:       \"revision\": \"head\",\n281:       \"path\": \"aruba/aoscx/docker/launch.py\",\n282:       \"bytes\": 6223,\n283:       \"lines\": 189\n284:     },\n285:     {\n286:       \"revision\": \"head\",\n287:       \"path\": \"aruba/aoscx/Makefile\",\n288:       \"bytes\": 316,\n289:       \"lines\": 11\n290:     },\n291:     {\n292:       \"revision\": \"head\",\n293:       \"path\": \"aruba/aoscx/README.md\",\n294:       \"bytes\": 1031,\n295:       \"lines\": 28\n296:     },\n297:     {\n298:       \"revision\": \"head\",\n299:       \"path\": \"build-base-image.sh\",\n300:       \"bytes\": 300,\n301:       \"lines\": 13\n302:     },\n303:     {\n304:       \"revision\": \"head\",\n305:       \"path\": \"cisco/asav/docker/Dockerfile\",\n306:       \"bytes\": 80,\n307:       \"lines\": 5\n308:     },\n309:     {\n310:       \"revision\": \"head\",\n311:       \"path\": \"cisco/asav/docker/launch.py\",\n312:       \"bytes\": 8663,\n313:       \"lines\": 268\n314:     },\n315:     {\n316:       \"revision\": \"head\",\n317:       \"path\": \"cisco/asav/Makefile\",\n318:       \"bytes\": 249,\n319:       \"lines\": 11\n320:     },\n321:     {\n322:       \"revision\": \"head\",\n323:       \"path\": \"cisco/asav/README.md\",\n324:       \"bytes\": 2133,\n325:       \"lines\": 68\n326:     },\n327:     {\n328:       \"revision\": \"head\",\n329:       \"path\": \"cisco/c8000v/docker/Dockerfile\",\n330:       \"bytes\": 193,\n331:       \"lines\": 12\n332:     },\n333:     {\n334:       \"revision\": \"head\",\n335:       \"path\": \"cisco/c8000v/docker/launch.py\",\n336:       \"bytes\": 16574,\n337:       \"lines\": 480\n338:     },\n339:     {\n340:       \"revision\": \"head\",\n341:       \"path\": \"cisco/c8000v/Makefile\",\n342:       \"bytes\": 2178,\n343:       \"lines\": 51\n344:     },\n345:     {\n346:       \"revision\": \"head\",\n347:       \"path\": \"cisco/c8000v/README.md\",\n348:       \"bytes\": 8825,\n349:       \"lines\": 222\n350:     },\n351:     {\n352:       \"revision\": \"head\",\n353:       \"path\": \"cisco/cat9kv/docker/Dockerfile\",\n354:       \"bytes\": 298,\n355:       \"lines\": 11\n356:     },\n357:     {\n358:       \"revision\": \"head\",\n359:       \"path\": \"cisco/cat9kv/docker/launch.py\",\n360:       \"bytes\": 8036,\n361:       \"lines\": 270\n362:     },\n363:     {\n364:       \"revision\": \"head\",\n365:       \"path\": \"cisco/cat9kv/Makefile\",\n366:       \"bytes\": 460,\n367:       \"lines\": 13\n368:     },\n369:     {\n370:       \"revision\": \"head\",\n371:       \"path\": \"cisco/cat9kv/README.md\",\n372:       \"bytes\": 4101,\n373:       \"lines\": 119\n374:     },\n375:     {\n376:       \"revision\": \"head\",\n377:       \"path\": \"cisco/csr1000v/docker/Dockerfile\",\n378:       \"bytes\": 155,\n379:       \"lines\": 9\n380:     },\n381:     {\n382:       \"revision\": \"head\",\n383:       \"path\": \"cisco/csr1000v/docker/launch.py\",\n384:       \"bytes\": 8713,\n385:       \"lines\": 314\n386:     },\n387:     {\n388:       \"revision\": \"head\",\n389:       \"path\": \"cisco/csr1000v/Makefile\",\n390:       \"bytes\": 721,\n391:       \"lines\": 21\n392:     },\n393:     {\n394:       \"revision\": \"head\",\n395:       \"path\": \"cisco/csr1000v/README.md\",\n396:       \"bytes\": 3441,\n397:       \"lines\": 78\n398:     },\n399:     {\n400:       \"revision\": \"head\",\n401:       \"path\": \"cisco/ftdv/docker/Dockerfile\",\n402:       \"bytes\": 129,\n403:       \"lines\": 8\n404:     },\n405:     {\n406:       \"revision\": \"head\",\n407:       \"path\": \"cisco/ftdv/docker/launch.py\",\n408:       \"bytes\": 11036,\n409:       \"lines\": 324\n410:     },\n411:     {\n412:       \"revision\": \"head\",\n413:       \"path\": \"cisco/ftdv/Makefile\",\n414:       \"bytes\": 352,\n415:       \"lines\": 12\n416:     },\n417:     {\n418:       \"revision\": \"head\",\n419:       \"path\": \"cisco/ftdv/README.md\",\n420:       \"bytes\": 1393,\n421:       \"lines\": 46\n422:     },\n423:     {\n424:       \"revision\": \"head\",\n425:       \"path\": \"cisco/iol/docker/Dockerfile\",\n426:       \"bytes\": 903,\n427:       \"lines\": 37\n428:     },\n429:     {\n430:       \"revision\": \"head\",\n431:       \"path\": \"cisco/iol/docker/entrypoint.sh\",\n432:       \"bytes\": 90,\n433:       \"lines\": 3\n434:     },\n435:     {\n436:       \"revision\": \"head\",\n437:       \"path\": \"cisco/iol/Makefile\",\n438:       \"bytes\": 2312,\n439:       \"lines\": 55\n440:     },\n441:     {\n442:       \"revision\": \"head\",\n443:       \"path\": \"cisco/iol/README.md\",\n444:       \"bytes\": 2779,\n445:       \"lines\": 66\n446:     },\n447:     {\n448:       \"revision\": \"head\",\n449:       \"path\": \"cisco/n9kv/docker/Dockerfile\",\n450:       \"bytes\": 196,\n451:       \"lines\": 10\n452:     },\n453:     {\n454:       \"revision\": \"head\",\n455:       \"path\": \"cisco/n9kv/docker/launch.py\",\n456:       \"bytes\": 7707,\n457:       \"lines\": 248\n458:     },\n459:     {\n460:       \"revision\": \"head\",\n461:       \"path\": \"cisco/n9kv/Makefile\",\n462:       \"bytes\": 368,\n463:       \"lines\": 12\n464:     },\n465:     {\n466:       \"revision\": \"head\",\n467:       \"path\": \"cisco/n9kv/README.md\",\n468:       \"bytes\": 1251,\n469:       \"lines\": 45\n470:     },\n471:     {\n472:       \"revision\": \"head\",\n473:       \"path\": \"cisco/nxos/docker/Dockerfile\",\n474:       \"bytes\": 120,\n475:       \"lines\": 7\n476:     },\n477:     {\n478:       \"revision\": \"head\",\n479:       \"path\": \"cisco/nxos/docker/launch.py\",\n480:       \"bytes\": 5944,\n481:       \"lines\": 203\n482:     },\n483:     {\n484:       \"revision\": \"head\",\n485:       \"path\": \"cisco/nxos/Makefile\",\n486:       \"bytes\": 371,\n487:       \"lines\": 13\n488:     },\n489:     {\n490:       \"revision\": \"head\",\n491:       \"path\": \"cisco/nxos/README.md\",\n492:       \"bytes\": 1181,\n493:       \"lines\": 37\n494:     },\n495:     {\n496:       \"revision\": \"head\",\n497:       \"path\": \"cisco/sdwan-components/docker/Dockerfile\",\n498:       \"bytes\": 442,\n499:       \"lines\": 22\n500:     },\n501:     {\n502:       \"revision\": \"head\",\n503:       \"path\": \"cisco/sdwan-components/docker/launch.py\",\n504:       \"bytes\": 10580,\n505:       \"lines\": 329\n506:     },\n507:     {\n508:       \"revision\": \"head\",\n509:       \"path\": \"cisco/sdwan-components/docker/templates/controller-zcloud.xml.j2\",\n510:       \"bytes\": 1542,\n511:       \"lines\": 59\n512:     },\n513:     {\n514:       \"revision\": \"head\",\n515:       \"path\": \"cisco/sdwan-components/docker/templates/manager-zcloud.xml.j2\",\n516:       \"bytes\": 1544,\n517:       \"lines\": 59\n518:     },\n519:     {\n520:       \"revision\": \"head\",\n521:       \"path\": \"cisco/sdwan-components/docker/templates/validator-zcloud.xml.j2\",\n522:       \"bytes\": 1574,\n523:       \"lines\": 62\n524:     },\n525:     {\n526:       \"revision\": \"head\",\n527:       \"path\": \"cisco/sdwan-components/Makefile\",\n528:       \"bytes\": 2260,\n529:       \"lines\": 44\n530:     },\n531:     {\n532:       \"revision\": \"head\",\n533:       \"path\": \"cisco/sdwan-components/README.md\",\n534:       \"bytes\": 1908,\n535:       \"lines\": 91\n536:     },\n537:     {\n538:       \"revision\": \"head\",\n539:       \"path\": \"cisco/vios/docker/Dockerfile\",\n540:       \"bytes\": 116,\n541:       \"lines\": 7\n542:     },\n543:     {\n544:       \"revision\": \"head\",\n545:       \"path\": \"cisco/vios/docker/launch.py\",\n546:       \"bytes\": 7023,\n547:       \"lines\": 221\n548:     },\n549:     {\n550:       \"revision\": \"head\",\n551:       \"path\": \"cisco/vios/Makefile\",\n552:       \"bytes\": 509,\n553:       \"lines\": 17\n554:     },\n555:     {\n556:       \"revision\": \"head\",\n557:       \"path\": \"cisco/vios/README.md\",\n558:       \"bytes\": 4730,\n559:       \"lines\": 143\n560:     },\n561:     {\n562:       \"revision\": \"head\",\n563:       \"path\": \"cisco/xrd-vrouter/docker/cloud-init-disable-net.cfg\",\n564:       \"bytes\": 28,\n565:       \"lines\": 1\n566:     },\n567:     {\n568:       \"revision\": \"head\",\n569:       \"path\": \"cisco/xrd-vrouter/docker/Dockerfile\",\n570:       \"bytes\": 402,\n571:       \"lines\": 11\n572:     },\n573:     {\n574:       \"revision\": \"head\",\n575:       \"path\": \"cisco/xrd-vrouter/docker/guest-init.sh\",\n576:       \"bytes\": 5708,\n577:       \"lines\": 122\n578:     },\n579:     {\n580:       \"revision\": \"head\",\n581:       \"path\": \"cisco/xrd-vrouter/docker/launch.py\",\n582:       \"bytes\": 10326,\n583:       \"lines\": 266\n584:     },\n585:     {\n586:       \"revision\": \"head\",\n587:       \"path\": \"cisco/xrd-vrouter/docker/make-golden.sh\",\n588:       \"bytes\": 5404,\n589:       \"lines\": 139\n590:     },\n591:     {\n592:       \"revision\": \"head\",\n593:       \"path\": \"cisco/xrd-vrouter/docker/netplan-mgmt.yaml\",\n594:       \"bytes\": 457,\n595:       \"lines\": 13\n596:     },\n597:     {\n598:       \"revision\": \"head\",\n599:       \"path\": \"cisco/xrd-vrouter/docker/xrd-guest-init.service\",\n600:       \"bytes\": 261,\n601:       \"lines\": 13\n602:     },\n603:     {\n604:       \"revision\": \"head\",\n605:       \"path\": \"cisco/xrd-vrouter/docker/xrd-unconfined\",\n606:       \"bytes\": 274,\n607:       \"lines\": 16\n608:     },\n609:     {\n610:       \"revision\": \"head\",\n611:       \"path\": \"cisco/xrd-vrouter/Makefile\",\n612:       \"bytes\": 1286,\n613:       \"lines\": 33\n614:     },\n615:     {\n616:       \"revision\": \"head\",\n617:       \"path\": \"cisco/xrd-vrouter/README.md\",\n618:       \"bytes\": 4702,\n619:       \"lines\": 79\n620:     },\n621:     {\n622:       \"revision\": \"head\",\n623:       \"path\": \"cisco/xrv/docker/Dockerfile\",\n624:       \"bytes\": 126,\n625:       \"lines\": 7\n626:     },\n627:     {\n628:       \"revision\": \"head\",\n629:       \"path\": \"cisco/xrv/docker/launch.py\",\n630:       \"bytes\": 7862,\n631:       \"lines\": 259\n632:     },\n633:     {\n634:       \"revision\": \"head\",\n635:       \"path\": \"cisco/xrv/Makefile\",\n636:       \"bytes\": 910,\n637:       \"lines\": 27\n638:     },\n639:     {\n640:       \"revision\": \"head\",\n641:       \"path\": \"cisco/xrv/README.md\",\n642:       \"bytes\": 1498,\n643:       \"lines\": 29\n644:     },\n645:     {\n646:       \"revision\": \"head\",\n647:       \"path\": \"cisco/xrv9k/docker/Dockerfile\",\n648:       \"bytes\": 148,\n649:       \"lines\": 8\n650:     },\n651:     {\n652:       \"revision\": \"head\",\n653:       \"path\": \"cisco/xrv9k/docker/launch.py\",\n654:       \"bytes\": 13568,\n655:       \"lines\": 426\n656:     },\n657:     {\n658:       \"revision\": \"head\",\n659:       \"path\": \"cisco/xrv9k/LICENSE\",\n660:       \"bytes\": 1109,\n661:       \"lines\": 21\n662:     },\n663:     {\n664:       \"revision\": \"head\",\n665:       \"path\": \"cisco/xrv9k/Makefile\",\n666:       \"bytes\": 561,\n667:       \"lines\": 23\n668:     },\n669:     {\n670:       \"revision\": \"head\",\n671:       \"path\": \"cisco/xrv9k/README.md\",\n672:       \"bytes\": 2699,\n673:       \"lines\": 63\n674:     },\n675:     {\n676:       \"revision\": \"head\",\n677:       \"path\": \"CODE_OF_CONDUCT.md\",\n678:       \"bytes\": 95,\n679:       \"lines\": 3\n680:     },\n681:     {\n682:       \"revision\": \"head\",\n683:       \"path\": \"common/healthcheck.py\",\n684:       \"bytes\": 339,\n685:       \"lines\": 18\n686:     },\n687:     {\n688:       \"revision\": \"head\",\n689:       \"path\": \"common/vrnetlab.py\",\n690:       \"bytes\": 64326,\n691:       \"lines\": 1716\n692:     },\n693:     {\n694:       \"revision\": \"head\",\n695:       \"path\": \"CONTRIBUTING.md\",\n696:       \"bytes\": 709,\n697:       \"lines\": 17\n698:     },\n699:     {\n700:       \"revision\": \"head\",\n701:       \"path\": \"dell/dell_sonic/docker/backup.sh\",\n702:       \"bytes\": 2833,\n703:       \"lines\": 107\n704:     },\n705:     {\n706:       \"revision\": \"head\",\n707:       \"path\": \"dell/dell_sonic/docker/Dockerfile\",\n708:       \"bytes\": 122,\n709:       \"lines\": 8\n710:     },\n711:     {\n712:       \"revision\": \"head\",\n713:       \"path\": \"dell/dell_sonic/docker/launch.py\",\n714:       \"bytes\": 5835,\n715:       \"lines\": 185\n716:     },\n717:     {\n718:       \"revision\": \"head\",\n719:       \"path\": \"dell/dell_sonic/Makefile\",\n720:       \"bytes\": 380,\n721:       \"lines\": 12\n722:     },\n723:     {\n724:       \"revision\": \"head\",\n725:       \"path\": \"dell/dell_sonic/README.md\",\n726:       \"bytes\": 1030,\n727:       \"lines\": 23\n728:     },\n729:     {\n730:       \"revision\": \"head\",\n731:       \"path\": \"dell/ftosv/docker/Dockerfile\",\n732:       \"bytes\": 309,\n733:       \"lines\": 10\n734:     },\n735:     {\n736:       \"revision\": \"head\",\n737:       \"path\": \"dell/ftosv/docker/launch.py\",\n738:       \"bytes\": 8356,\n739:       \"lines\": 230\n740:     },\n741:     {\n742:       \"revision\": \"head\",\n743:       \"path\": \"dell/ftosv/Makefile\",\n744:       \"bytes\": 287,\n745:       \"lines\": 11\n746:     },\n747:     {\n748:       \"revision\": \"head\",\n749:       \"path\": \"dell/ftosv/README.md\",\n750:       \"bytes\": 17648,\n751:       \"lines\": 235\n752:     },\n753:     {\n754:       \"revision\": \"head\",\n755:       \"path\": \"dev-notes.md\",\n756:       \"bytes\": 352,\n757:       \"lines\": 13\n758:     },\n759:     {\n760:       \"revision\": \"head\",\n761:       \"path\": \"extreme/exos/docker/Dockerfile\",\n762:       \"bytes\": 80,\n763:       \"lines\": 5\n764:     },\n765:     {\n766:       \"revision\": \"head\",\n767:       \"path\": \"extreme/exos/docker/launch.py\",\n768:       \"bytes\": 7926,\n769:       \"lines\": 219\n770:     },\n771:     {\n772:       \"revision\": \"head\",\n773:       \"path\": \"extreme/exos/Makefile\",\n774:       \"bytes\": 261,\n775:       \"lines\": 11\n776:     },\n777:     {\n778:       \"revision\": \"head\",\n779:       \"path\": \"extreme/exos/README.md\",\n780:       \"bytes\": 1735,\n781:       \"lines\": 42\n782:     },\n783:     {\n784:       \"revision\": \"head\",\n785:       \"path\": \"extreme/voss/docker/Dockerfile\",\n786:       \"bytes\": 80,\n787:       \"lines\": 5\n788:     },\n789:     {\n790:       \"revision\": \"head\",\n791:       \"path\": \"extreme/voss/docker/launch.py\",\n792:       \"bytes\": 9114,\n793:       \"lines\": 245\n794:     },\n795:     {\n796:       \"revision\": \"head\",\n797:       \"path\": \"extreme/voss/Makefile\",\n798:       \"bytes\": 296,\n799:       \"lines\": 11\n800:     },\n801:     {\n802:       \"revision\": \"head\",\n803:       \"path\": \"extreme/voss/README.md\",\n804:       \"bytes\": 790,\n805:       \"lines\": 27\n806:     },\n807:     {\n808:       \"revision\": \"head\",\n809:       \"path\": \"f5_bigip/docker/Dockerfile\",\n810:       \"bytes\": 229,\n811:       \"lines\": 13\n812:     },\n813:     {\n814:       \"revision\": \"head\",\n815:       \"path\": \"f5_bigip/docker/launch.py\",\n816:       \"bytes\": 16156,\n817:       \"lines\": 474\n818:     },\n819:     {\n820:       \"revision\": \"head\",\n821:       \"path\": \"f5_bigip/Makefile\",\n822:       \"bytes\": 529,\n823:       \"lines\": 17\n824:     },\n825:     {\n826:       \"revision\": \"head\",\n827:       \"path\": \"f5_bigip/README.md\",\n828:       \"bytes\": 1273,\n829:       \"lines\": 31\n830:     },\n831:     {\n832:       \"revision\": \"head\",\n833:       \"path\": \"fortinet/common/__init__.py\",\n834:       \"bytes\": 66,\n835:       \"lines\": 1\n836:     },\n837:     {\n838:       \"revision\": \"head\",\n839:       \"path\": \"fortinet/common/config_diff.py\",\n840:       \"bytes\": 4069,\n841:       \"lines\": 138\n842:     },\n843:     {\n844:       \"revision\": \"head\",\n845:       \"path\": \"fortinet/common/env.py\",\n846:       \"bytes\": 1523,\n847:       \"lines\": 48\n848:     },\n849:     {\n850:       \"revision\": \"head\",\n851:       \"path\": \"fortinet/common/features/__init__.py\",\n852:       \"bytes\": 1534,\n853:       \"lines\": 49\n854:     },\n855:     {\n856:       \"revision\": \"head\",\n857:       \"path\": \"fortinet/common/features/capture_config.py\",\n858:       \"bytes\": 14172,\n859:       \"lines\": 362\n860:     },\n861:     {\n862:       \"revision\": \"head\",\n863:       \"path\": \"fortinet/common/features/default_config.py\",\n864:       \"bytes\": 1077,\n865:       \"lines\": 33\n866:     },\n867:     {\n868:       \"revision\": \"head\",\n869:       \"path\": \"fortinet/common/features/disks.py\",\n870:       \"bytes\": 3193,\n871:       \"lines\": 86\n872:     },\n873:     {\n874:       \"revision\": \"head\",\n875:       \"path\": \"fortinet/common/features/fortiguard_hooks.py\",\n876:       \"bytes\": 3440,\n877:       \"lines\": 103\n878:     },\n879:     {\n880:       \"revision\": \"head\",\n881:       \"path\": \"fortinet/common/features/fortitoken.py\",\n882:       \"bytes\": 2951,\n883:       \"lines\": 95\n884:     },\n885:     {\n886:       \"revision\": \"head\",\n887:       \"path\": \"fortinet/common/features/image_info.py\",\n888:       \"bytes\": 2616,\n889:       \"lines\": 81\n890:     },\n891:     {\n892:       \"revision\": \"head\",\n893:       \"path\": \"fortinet/common/features/license.py\",\n894:       \"bytes\": 10131,\n895:       \"lines\": 268\n896:     },\n897:     {\n898:       \"revision\": \"head\",\n899:       \"path\": \"fortinet/common/features/mgmt_dns.py\",\n900:       \"bytes\": 2139,\n901:       \"lines\": 60\n902:     },\n903:     {\n904:       \"revision\": \"head\",\n905:       \"path\": \"fortinet/common/features/mgmt_net.py\",\n906:       \"bytes\": 4174,\n907:       \"lines\": 114\n908:     },\n909:     {\n910:       \"revision\": \"head\",\n911:       \"path\": \"fortinet/common/features/product.py\",\n912:       \"bytes\": 3918,\n913:       \"lines\": 107\n914:     },\n915:     {\n916:       \"revision\": \"head\",\n917:       \"path\": \"fortinet/common/file_watcher.py\",\n918:       \"bytes\": 2307,\n919:       \"lines\": 69\n920:     },\n921:     {\n922:       \"revision\": \"head\",\n923:       \"path\": \"fortinet/common/fos_healthcheck.py\",\n924:       \"bytes\": 3984,\n925:       \"lines\": 111\n926:     },\n927:     {\n928:       \"revision\": \"head\",\n929:       \"path\": \"fortinet/common/host_forwarded_bridge.py\",\n930:       \"bytes\": 3614,\n931:       \"lines\": 95\n932:     },\n933:     {\n934:       \"revision\": \"head\",\n935:       \"path\": \"fortinet/common/net_mgmt_strategy.py\",\n936:       \"bytes\": 1299,\n937:       \"lines\": 48\n938:     },\n939:     {\n940:       \"revision\": \"head\",\n941:       \"path\": \"fortinet/common/passthrough_redirect.py\",\n942:       \"bytes\": 8909,\n943:       \"lines\": 201\n944:     },\n945:     {\n946:       \"revision\": \"head\",\n947:       \"path\": \"fortinet/common/tftp.py\",\n948:       \"bytes\": 2742,\n949:       \"lines\": 88\n950:     },\n951:     {\n952:       \"revision\": \"head\",\n953:       \"path\": \"fortinet/fortigate/.gitignore\",\n954:       \"bytes\": 7,\n955:       \"lines\": 1\n956:     },\n957:     {\n958:       \"revision\": \"head\",\n959:       \"path\": \"fortinet/fortigate/docker/Dockerfile\",\n960:       \"bytes\": 1146,\n961:       \"lines\": 27\n962:     },\n963:     {\n964:       \"revision\": \"head\",\n965:       \"path\": \"fortinet/fortigate/docker/launch.py\",\n966:       \"bytes\": 106,\n967:       \"lines\": 7\n968:     },\n969:     {\n970:       \"revision\": \"head\",\n971:       \"path\": \"fortinet/fortigate/Makefile\",\n972:       \"bytes\": 1146,\n973:       \"lines\": 24\n974:     },\n975:     {\n976:       \"revision\": \"head\",\n977:       \"path\": \"fortinet/fortiproxy/.gitignore\",\n978:       \"bytes\": 8,\n979:       \"lines\": 1\n980:     },\n981:     {\n982:       \"revision\": \"head\",\n983:       \"path\": \"fortinet/fortiproxy/docker/Dockerfile\",\n984:       \"bytes\": 418,\n985:       \"lines\": 17\n986:     },\n987:     {\n988:       \"revision\": \"head\",\n989:       \"path\": \"fortinet/fortiproxy/docker/launch.py\",\n990:       \"bytes\": 107,\n991:       \"lines\": 7\n992:     },\n993:     {\n994:       \"revision\": \"head\",\n995:       \"path\": \"fortinet/fortiproxy/docker/README.md\",\n996:       \"bytes\": 189,\n997:       \"lines\": 4\n998:     },\n999:     {\n1000:       \"revision\": \"head\",\n1001:       \"path\": \"fortinet/fortiproxy/Makefile\",\n1002:       \"bytes\": 1156,\n1003:       \"lines\": 25\n1004:     },\n1005:     {\n1006:       \"revision\": \"head\",\n1007:       \"path\": \"fortinet/fortiproxy/README.md\",\n1008:       \"bytes\": 1044,\n1009:       \"lines\": 22\n1010:     },\n1011:     {\n1012:       \"revision\": \"head\",\n1013:       \"path\": \"fortinet/tests/test_common_capture_pki.py\",\n1014:       \"bytes\": 12387,\n1015:       \"lines\": 239\n1016:     },\n1017:     {\n1018:       \"revision\": \"head\",\n1019:       \"path\": \"fortinet/tests/test_common_commander_scheduler.py\",\n1020:       \"bytes\": 9852,\n1021:       \"lines\": 183\n1022:     },\n1023:     {\n1024:       \"revision\": \"head\",\n1025:       \"path\": \"fortinet/tests/test_common_commands.py\",\n1026:       \"bytes\": 5500,\n1027:       \"lines\": 137\n1028:     },\n1029:     {\n1030:       \"revision\": \"head\",\n1031:       \"path\": \"fortinet/tests/test_common_environment_watchers.py\",\n1032:       \"bytes\": 5635,\n1033:       \"lines\": 122\n1034:     },\n1035:     {\n1036:       \"revision\": \"head\",\n1037:       \"path\": \"fortinet/tests/test_common_features.py\",\n1038:       \"bytes\": 17522,\n1039:       \"lines\": 346\n1040:     },\n1041:     {\n1042:       \"revision\": \"head\",\n1043:       \"path\": \"fortinet/tests/test_common_license.py\",\n1044:       \"bytes\": 9565,\n1045:       \"lines\": 180\n1046:     },\n1047:     {\n1048:       \"revision\": \"head\",\n1049:       \"path\": \"fortinet/tests/test_common_network_launch.py\",\n1050:       \"bytes\": 12810,\n1051:       \"lines\": 239\n1052:     },\n1053:     {\n1054:       \"revision\": \"head\",\n1055:       \"path\": \"fortinet/tests/test_fos_commander.py\",\n1056:       \"bytes\": 3608,\n1057:       \"lines\": 93\n1058:     },\n1059:     {\n1060:       \"revision\": \"head\",\n1061:       \"path\": \"fortinet/tests/test_vrnetlab.py\",\n1062:       \"bytes\": 4478,\n1063:       \"lines\": 127\n1064:     },\n1065:     {\n1066:       \"revision\": \"head\",\n1067:       \"path\": \"freebsd/docker/backup.sh\",\n1068:       \"bytes\": 2071,\n1069:       \"lines\": 84\n1070:     },\n1071:     {\n1072:       \"revision\": \"head\",\n1073:       \"path\": \"freebsd/docker/Dockerfile\",\n1074:       \"bytes\": 442,\n1075:       \"lines\": 22\n1076:     },\n1077:     {\n1078:       \"revision\": \"head\",\n1079:       \"path\": \"freebsd/docker/launch.py\",\n1080:       \"bytes\": 8117,\n1081:       \"lines\": 257\n1082:     },\n1083:     {\n1084:       \"revision\": \"head\",\n1085:       \"path\": \"freebsd/download.sh\",\n1086:       \"bytes\": 682,\n1087:       \"lines\": 22\n1088:     },\n1089:     {\n1090:       \"revision\": \"head\",\n1091:       \"path\": \"freebsd/Makefile\",\n1092:       \"bytes\": 342,\n1093:       \"lines\": 17\n1094:     },\n1095:     {\n1096:       \"revision\": \"head\",\n1097:       \"path\": \"freebsd/README.md\",\n1098:       \"bytes\": 1714,\n1099:       \"lines\": 52\n1100:     },\n1101:     {\n1102:       \"revision\": \"head\",\n1103:       \"path\": \"hp/vsr1000/docker/Dockerfile\",\n1104:       \"bytes\": 187,\n1105:       \"lines\": 8\n1106:     },\n1107:     {\n1108:       \"revision\": \"head\",\n1109:       \"path\": \"hp/vsr1000/docker/launch.py\",\n1110:       \"bytes\": 5525,\n1111:       \"lines\": 160\n1112:     },\n1113:     {\n1114:       \"revision\": \"head\",\n1115:       \"path\": \"hp/vsr1000/Makefile\",\n1116:       \"bytes\": 342,\n1117:       \"lines\": 13\n1118:     },\n1119:     {\n1120:       \"revision\": \"head\",\n1121:       \"path\": \"hp/vsr1000/README.md\",\n1122:       \"bytes\": 1049,\n1123:       \"lines\": 34\n1124:     },\n1125:     {\n1126:       \"revision\": \"head\",\n1127:       \"path\": \"huawei/huawei_vrp/docker/Dockerfile\",\n1128:       \"bytes\": 133,\n1129:       \"lines\": 7\n1130:     },\n1131:     {\n1132:       \"revision\": \"head\",\n1133:       \"path\": \"huawei/huawei_vrp/docker/launch.py\",\n1134:       \"bytes\": 18313,\n1135:       \"lines\": 468\n1136:     },\n1137:     {\n1138:       \"revision\": \"head\",\n1139:       \"path\": \"huawei/huawei_vrp/Makefile\",\n1140:       \"bytes\": 334,\n1141:       \"lines\": 12\n1142:     },\n1143:     {\n1144:       \"revision\": \"head\",\n1145:       \"path\": \"huawei/huawei_vrp/README.md\",\n1146:       \"bytes\": 426,\n1147:       \"lines\": 27\n1148:     },\n1149:     {\n1150:       \"revision\": \"head\",\n1151:       \"path\": \"ipinfusion/ocnos/docker/Dockerfile\",\n1152:       \"bytes\": 127,\n1153:       \"lines\": 7\n1154:     },\n1155:     {\n1156:       \"revision\": \"head\",\n1157:       \"path\": \"ipinfusion/ocnos/docker/launch.py\",\n1158:       \"bytes\": 7658,\n1159:       \"lines\": 223\n1160:     },\n1161:     {\n1162:       \"revision\": \"head\",\n1163:       \"path\": \"ipinfusion/ocnos/Makefile\",\n1164:       \"bytes\": 522,\n1165:       \"lines\": 16\n1166:     },\n1167:     {\n1168:       \"revision\": \"head\",\n1169:       \"path\": \"ipinfusion/ocnos/README.md\",\n1170:       \"bytes\": 1417,\n1171:       \"lines\": 49\n1172:     },\n1173:     {\n1174:       \"revision\": \"head\",\n1175:       \"path\": \"juniper/apstra/docker/Dockerfile\",\n1176:       \"bytes\": 369,\n1177:       \"lines\": 14\n1178:     },\n1179:     {\n1180:       \"revision\": \"head\",\n1181:       \"path\": \"juniper/apstra/docker/launch.py\",\n1182:       \"bytes\": 10481,\n1183:       \"lines\": 262\n1184:     },\n1185:     {\n1186:       \"revision\": \"head\",\n1187:       \"path\": \"juniper/apstra/Makefile\",\n1188:       \"bytes\": 1225,\n1189:       \"lines\": 36\n1190:     },\n1191:     {\n1192:       \"revision\": \"head\",\n1193:       \"path\": \"juniper/apstra/README.md\",\n1194:       \"bytes\": 10010,\n1195:       \"lines\": 307\n1196:     },\n1197:     {\n1198:       \"revision\": \"head\",\n1199:       \"path\": \"juniper/vjunosevolved/docker/Dockerfile\",\n1200:       \"bytes\": 325,\n1201:       \"lines\": 14\n1202:     },\n1203:     {\n1204:       \"revision\": \"head\",\n1205:       \"path\": \"juniper/vjunosevolved/docker/init.conf\",\n1206:       \"bytes\": 855,\n1207:       \"lines\": 44\n1208:     },\n1209:     {\n1210:       \"revision\": \"head\",\n1211:       \"path\": \"juniper/vjunosevolved/docker/launch.py\",\n1212:       \"bytes\": 8866,\n1213:       \"lines\": 246\n1214:     },\n1215:     {\n1216:       \"revision\": \"head\",\n1217:       \"path\": \"juniper/vjunosevolved/docker/make-config.sh\",\n1218:       \"bytes\": 1402,\n1219:       \"lines\": 60\n1220:     },\n1221:     {\n1222:       \"revision\": \"head\",\n1223:       \"path\": \"juniper/vjunosevolved/Makefile\",\n1224:       \"bytes\": 352,\n1225:       \"lines\": 15\n1226:     },\n1227:     {\n1228:       \"revision\": \"head\",\n1229:       \"path\": \"juniper/vjunosevolved/README.md\",\n1230:       \"bytes\": 718,\n1231:       \"lines\": 19\n1232:     },\n1233:     {\n1234:       \"revision\": \"head\",\n1235:       \"path\": \"juniper/vjunosrouter/docker/Dockerfile\",\n1236:       \"bytes\": 325,\n1237:       \"lines\": 14\n1238:     },\n1239:     {\n1240:       \"revision\": \"head\",\n1241:       \"path\": \"juniper/vjunosrouter/docker/init.conf\",\n1242:       \"bytes\": 915,\n1243:       \"lines\": 51\n1244:     },\n1245:     {\n1246:       \"revision\": \"head\",\n1247:       \"path\": \"juniper/vjunosrouter/docker/launch.py\",\n1248:       \"bytes\": 7341,\n1249:       \"lines\": 212\n1250:     },\n1251:     {\n1252:       \"revision\": \"head\",\n1253:       \"path\": \"juniper/vjunosrouter/docker/make-config.sh\",\n1254:       \"bytes\": 1402,\n1255:       \"lines\": 60\n1256:     },\n1257:     {\n1258:       \"revision\": \"head\",\n1259:       \"path\": \"juniper/vjunosrouter/Makefile\",\n1260:       \"bytes\": 824,\n1261:       \"lines\": 31\n1262:     },\n1263:     {\n1264:       \"revision\": \"head\",\n1265:       \"path\": \"juniper/vjunosrouter/README.md\",\n1266:       \"bytes\": 494,\n1267:       \"lines\": 15\n1268:     },\n1269:     {\n1270:       \"revision\": \"head\",\n1271:       \"path\": \"juniper/vjunosswitch/docker/Dockerfile\",\n1272:       \"bytes\": 325,\n1273:       \"lines\": 14\n1274:     },\n1275:     {\n1276:       \"revision\": \"head\",\n1277:       \"path\": \"juniper/vjunosswitch/docker/init.conf\",\n1278:       \"bytes\": 915,\n1279:       \"lines\": 51\n1280:     },\n1281:     {\n1282:       \"revision\": \"head\",\n1283:       \"path\": \"juniper/vjunosswitch/docker/launch.py\",\n1284:       \"bytes\": 7358,\n1285:       \"lines\": 212\n1286:     },\n1287:     {\n1288:       \"revision\": \"head\",\n1289:       \"path\": \"juniper/vjunosswitch/docker/make-config.sh\",\n1290:       \"bytes\": 1402,\n1291:       \"lines\": 60\n1292:     },\n1293:     {\n1294:       \"revision\": \"head\",\n1295:       \"path\": \"juniper/vjunosswitch/Makefile\",\n1296:       \"bytes\": 886,\n1297:       \"lines\": 34\n1298:     },\n1299:     {\n1300:       \"revision\": \"head\",\n1301:       \"path\": \"juniper/vjunosswitch/README.md\",\n1302:       \"bytes\": 513,\n1303:       \"lines\": 17\n1304:     },\n1305:     {\n1306:       \"revision\": \"head\",\n1307:       \"path\": \"juniper/vmx/docker/Dockerfile\",\n1308:       \"bytes\": 295,\n1309:       \"lines\": 12\n1310:     },\n1311:     {\n1312:       \"revision\": \"head\",\n1313:       \"path\": \"juniper/vmx/docker/launch.py\",\n1314:       \"bytes\": 17750,\n1315:       \"lines\": 496\n1316:     },\n1317:     {\n1318:       \"revision\": \"head\",\n1319:       \"path\": \"juniper/vmx/Makefile\",\n1320:       \"bytes\": 590,\n1321:       \"lines\": 22\n1322:     },\n1323:     {\n1324:       \"revision\": \"head\",\n1325:       \"path\": \"juniper/vmx/README.md\",\n1326:       \"bytes\": 1880,\n1327:       \"lines\": 45\n1328:     },\n1329:     {\n1330:       \"revision\": \"head\",\n1331:       \"path\": \"juniper/vmx/vmx-extract.sh\",\n1332:       \"bytes\": 894,\n1333:       \"lines\": 24\n1334:     },\n1335:     {\n1336:       \"revision\": \"head\",\n1337:       \"path\": \"juniper/vqfx/docker/Dockerfile\",\n1338:       \"bytes\": 328,\n1339:       \"lines\": 18\n1340:     },\n1341:     {\n1342:       \"revision\": \"head\",\n1343:       \"path\": \"juniper/vqfx/docker/launch.py\",\n1344:       \"bytes\": 10990,\n1345:       \"lines\": 305\n1346:     },\n1347:     {\n1348:       \"revision\": \"head\",\n1349:       \"path\": \"juniper/vqfx/Makefile\",\n1350:       \"bytes\": 2052,\n1351:       \"lines\": 35\n1352:     },\n1353:     {\n1354:       \"revision\": \"head\",\n1355:       \"path\": \"juniper/vqfx/README.md\",\n1356:       \"bytes\": 161,\n1357:       \"lines\": 6\n1358:     },\n1359:     {\n1360:       \"revision\": \"head\",\n1361:       \"path\": \"juniper/vsrx/docker/Dockerfile\",\n1362:       \"bytes\": 240,\n1363:       \"lines\": 11\n1364:     },\n1365:     {\n1366:       \"revision\": \"head\",\n1367:       \"path\": \"juniper/vsrx/docker/init.conf\",\n1368:       \"bytes\": 848,\n1369:       \"lines\": 43\n1370:     },\n1371:     {\n1372:       \"revision\": \"head\",\n1373:       \"path\": \"juniper/vsrx/docker/launch.py\",\n1374:       \"bytes\": 6670,\n1375:       \"lines\": 193\n1376:     },\n1377:     {\n1378:       \"revision\": \"head\",\n1379:       \"path\": \"juniper/vsrx/docker/make-config-iso.sh\",\n1380:       \"bytes\": 416,\n1381:       \"lines\": 24\n1382:     },\n1383:     {\n1384:       \"revision\": \"head\",\n1385:       \"path\": \"juniper/vsrx/Makefile\",\n1386:       \"bytes\": 303,\n1387:       \"lines\": 12\n1388:     },\n1389:     {\n1390:       \"revision\": \"head\",\n1391:       \"path\": \"juniper/vsrx/README.md\",\n1392:       \"bytes\": 1416,\n1393:       \"lines\": 29\n1394:     },\n1395:     {\n1396:       \"revision\": \"head\",\n1397:       \"path\": \"LICENSE\",\n1398:       \"bytes\": 1109,\n1399:       \"lines\": 21\n1400:     },\n1401:     {\n1402:       \"revision\": \"head\",\n1403:       \"path\": \"makefile-install.include\",\n1404:       \"bytes\": 3279,\n1405:       \"lines\": 48\n1406:     },\n1407:     {\n1408:       \"revision\": \"head\",\n1409:       \"path\": \"makefile-sanity.include\",\n1410:       \"bytes\": 370,\n1411:       \"lines\": 8\n1412:     },\n1413:     {\n1414:       \"revision\": \"head\",\n1415:       \"path\": \"makefile.include\",\n1416:       \"bytes\": 3274,\n1417:       \"lines\": 85\n1418:     },\n1419:     {\n1420:       \"revision\": \"head\",\n1421:       \"path\": \"mikrotik/routeros/docker/Dockerfile\",\n1422:       \"bytes\": 350,\n1423:       \"lines\": 15\n1424:     },\n1425:     {\n1426:       \"revision\": \"head\",\n1427:       \"path\": \"mikrotik/routeros/docker/launch.py\",\n1428:       \"bytes\": 11967,\n1429:       \"lines\": 313\n1430:     },\n1431:     {\n1432:       \"revision\": \"head\",\n1433:       \"path\": \"mikrotik/routeros/Makefile\",\n1434:       \"bytes\": 1687,\n1435:       \"lines\": 39\n1436:     },\n1437:     {\n1438:       \"revision\": \"head\",\n1439:       \"path\": \"mikrotik/routeros/README.md\",\n1440:       \"bytes\": 998,\n1441:       \"lines\": 35\n1442:     },\n1443:     {\n1444:       \"revision\": \"head\",\n1445:       \"path\": \"netapp/ontap/docker/Dockerfile\",\n1446:       \"bytes\": 724,\n1447:       \"lines\": 26\n1448:     },\n1449:     {\n1450:       \"revision\": \"head\",\n1451:       \"path\": \"netapp/ontap/docker/launch.py\",\n1452:       \"bytes\": 22293,\n1453:       \"lines\": 521\n1454:     },\n1455:     {\n1456:       \"revision\": \"head\",\n1457:       \"path\": \"netapp/ontap/Makefile\",\n1458:       \"bytes\": 337,\n1459:       \"lines\": 12\n1460:     },\n1461:     {\n1462:       \"revision\": \"head\",\n1463:       \"path\": \"netapp/ontap/README.md\",\n1464:       \"bytes\": 7014,\n1465:       \"lines\": 171\n1466:     },\n1467:     {\n1468:       \"revision\": \"head\",\n1469:       \"path\": \"nokia/cmglinux/docker/Dockerfile\",\n1470:       \"bytes\": 412,\n1471:       \"lines\": 21\n1472:     },\n1473:     {\n1474:       \"revision\": \"head\",\n1475:       \"path\": \"nokia/cmglinux/docker/launch.py\",\n1476:       \"bytes\": 9068,\n1477:       \"lines\": 299\n1478:     },\n1479:     {\n1480:       \"revision\": \"head\",\n1481:       \"path\": \"nokia/cmglinux/Makefile\",\n1482:       \"bytes\": 304,\n1483:       \"lines\": 12\n1484:     },\n1485:     {\n1486:       \"revision\": \"head\",\n1487:       \"path\": \"nokia/cmglinux/README.md\",\n1488:       \"bytes\": 2931,\n1489:       \"lines\": 100\n1490:     },\n1491:     {\n1492:       \"revision\": \"head\",\n1493:       \"path\": \"nokia/sros/docker/Dockerfile\",\n1494:       \"bytes\": 152,\n1495:       \"lines\": 6\n1496:     },\n1497:     {\n1498:       \"revision\": \"head\",\n1499:       \"path\": \"nokia/sros/docker/launch.py\",\n1500:       \"bytes\": 72283,\n1501:       \"lines\": 1983\n1502:     },\n1503:     {\n1504:       \"revision\": \"head\",\n1505:       \"path\": \"nokia/sros/Makefile\",\n1506:       \"bytes\": 337,\n1507:       \"lines\": 13\n1508:     },\n1509:     {\n1510:       \"revision\": \"head\",\n1511:       \"path\": \"nokia/sros/README.md\",\n1512:       \"bytes\": 7221,\n1513:       \"lines\": 126\n1514:     },\n1515:     {\n1516:       \"revision\": \"head\",\n1517:       \"path\": \"nvidia/cumulus-vx/docker/Dockerfile\",\n1518:       \"bytes\": 375,\n1519:       \"lines\": 14\n1520:     },\n1521:     {\n1522:       \"revision\": \"head\",\n1523:       \"path\": \"nvidia/cumulus-vx/docker/launch.py\",\n1524:       \"bytes\": 24943,\n1525:       \"lines\": 649\n1526:     },\n1527:     {\n1528:       \"revision\": \"head\",\n1529:       \"path\": \"nvidia/cumulus-vx/Makefile\",\n1530:       \"bytes\": 1250,\n1531:       \"lines\": 35\n1532:     },\n1533:     {\n1534:       \"revision\": \"head\",\n1535:       \"path\": \"nvidia/cumulus-vx/README.md\",\n1536:       \"bytes\": 2977,\n1537:       \"lines\": 101\n1538:     },\n1539:     {\n1540:       \"revision\": \"head\",\n1541:       \"path\": \"openbsd/docker/backup.sh\",\n1542:       \"bytes\": 2069,\n1543:       \"lines\": 84\n1544:     },\n1545:     {\n1546:       \"revision\": \"head\",\n1547:       \"path\": \"openbsd/docker/Dockerfile\",\n1548:       \"bytes\": 428,\n1549:       \"lines\": 20\n1550:     },\n1551:     {\n1552:       \"revision\": \"head\",\n1553:       \"path\": \"openbsd/docker/launch.py\",\n1554:       \"bytes\": 6854,\n1555:       \"lines\": 218\n1556:     },\n1557:     {\n1558:       \"revision\": \"head\",\n1559:       \"path\": \"openbsd/download.sh\",\n1560:       \"bytes\": 769,\n1561:       \"lines\": 28\n1562:     },\n1563:     {\n1564:       \"revision\": \"head\",\n1565:       \"path\": \"openbsd/Makefile\",\n1566:       \"bytes\": 352,\n1567:       \"lines\": 17\n1568:     },\n1569:     {\n1570:       \"revision\": \"head\",\n1571:       \"path\": \"openbsd/README.md\",\n1572:       \"bytes\": 1769,\n1573:       \"lines\": 52\n1574:     },\n1575:     {\n1576:       \"revision\": \"head\",\n1577:       \"path\": \"openwrt/docker/Dockerfile\",\n1578:       \"bytes\": 152,\n1579:       \"lines\": 9\n1580:     },\n1581:     {\n1582:       \"revision\": \"head\",\n1583:       \"path\": \"openwrt/docker/launch.py\",\n1584:       \"bytes\": 49519,\n1585:       \"lines\": 1288\n1586:     },\n1587:     {\n1588:       \"revision\": \"head\",\n1589:       \"path\": \"openwrt/download.py\",\n1590:       \"bytes\": 2920,\n1591:       \"lines\": 82\n1592:     },\n1593:     {\n1594:       \"revision\": \"head\",\n1595:       \"path\": \"openwrt/Makefile\",\n1596:       \"bytes\": 533,\n1597:       \"lines\": 20\n1598:     },\n1599:     {\n1600:       \"revision\": \"head\",\n1601:       \"path\": \"openwrt/README.md\",\n1602:       \"bytes\": 5302,\n1603:       \"lines\": 144\n1604:     },\n1605:     {\n1606:       \"revision\": \"head\",\n1607:       \"path\": \"opnsense/docker/Dockerfile\",\n1608:       \"bytes\": 401,\n1609:       \"lines\": 19\n1610:     },\n1611:     {\n1612:       \"revision\": \"head\",\n1613:       \"path\": \"opnsense/docker/launch.py\",\n1614:       \"bytes\": 10379,\n1615:       \"lines\": 280\n1616:     },\n1617:     {\n1618:       \"revision\": \"head\",\n1619:       \"path\": \"opnsense/Makefile\",\n1620:       \"bytes\": 551,\n1621:       \"lines\": 18\n1622:     },\n1623:     {\n1624:       \"revision\": \"head\",\n1625:       \"path\": \"opnsense/README.md\",\n1626:       \"bytes\": 2391,\n1627:       \"lines\": 70\n1628:     },\n1629:     {\n1630:       \"revision\": \"head\",\n1631:       \"path\": \"paloalto/pan/docker/Dockerfile\",\n1632:       \"bytes\": 174,\n1633:       \"lines\": 9\n1634:     },\n1635:     {\n1636:       \"revision\": \"head\",\n1637:       \"path\": \"paloalto/pan/docker/launch.py\",\n1638:       \"bytes\": 13856,\n1639:       \"lines\": 352\n1640:     },\n1641:     {\n1642:       \"revision\": \"head\",\n1643:       \"path\": \"paloalto/pan/Makefile\",\n1644:       \"bytes\": 288,\n1645:       \"lines\": 12\n1646:     },\n1647:     {\n1648:       \"revision\": \"head\",\n1649:       \"path\": \"paloalto/pan/README.md\",\n1650:       \"bytes\": 710,\n1651:       \"lines\": 27\n1652:     },\n1653:     {\n1654:       \"revision\": \"head\",\n1655:       \"path\": \"plvision/plvision_sonic/docker/backup.sh\",\n1656:       \"bytes\": 2833,\n1657:       \"lines\": 107\n1658:     },\n1659:     {\n1660:       \"revision\": \"head\",\n1661:       \"path\": \"plvision/plvision_sonic/docker/Dockerfile\",\n1662:       \"bytes\": 503,\n1663:       \"lines\": 17\n1664:     },\n1665:     {\n1666:       \"revision\": \"head\",\n1667:       \"path\": \"plvision/plvision_sonic/docker/launch.py\",\n1668:       \"bytes\": 6323,\n1669:       \"lines\": 189\n1670:     },\n1671:     {\n1672:       \"revision\": \"head\",\n1673:       \"path\": \"plvision/plvision_sonic/Makefile\",\n1674:       \"bytes\": 458,\n1675:       \"lines\": 13\n1676:     },\n1677:     {\n1678:       \"revision\": \"head\",\n1679:       \"path\": \"plvision/plvision_sonic/README.md\",\n1680:       \"bytes\": 1506,\n1681:       \"lines\": 35\n1682:     },\n1683:     {\n1684:       \"revision\": \"head\",\n1685:       \"path\": \"pyproject.toml\",\n1686:       \"bytes\": 417,\n1687:       \"lines\": 17\n1688:     },\n1689:     {\n1690:       \"revision\": \"head\",\n1691:       \"path\": \"README.md\",\n1692:       \"bytes\": 8444,\n1693:       \"lines\": 169\n1694:     },\n1695:     {\n1696:       \"revision\": \"head\",\n1697:       \"path\": \"sonic/docker/backup.sh\",\n1698:       \"bytes\": 2833,\n1699:       \"lines\": 107\n1700:     },\n1701:     {\n1702:       \"revision\": \"head\",\n1703:       \"path\": \"sonic/docker/Dockerfile\",\n1704:       \"bytes\": 415,\n1705:       \"lines\": 15\n1706:     },\n1707:     {\n1708:       \"revision\": \"head\",\n1709:       \"path\": \"sonic/docker/launch.py\",\n1710:       \"bytes\": 6278,\n1711:       \"lines\": 189\n1712:     },\n1713:     {\n1714:       \"revision\": \"head\",\n1715:       \"path\": \"sonic/Makefile\",\n1716:       \"bytes\": 269,\n1717:       \"lines\": 12\n1718:     },\n1719:     {\n1720:       \"revision\": \"head\",\n1721:       \"path\": \"sonic/README.md\",\n1722:       \"bytes\": 1305,\n1723:       \"lines\": 31\n1724:     },\n1725:     {\n1726:       \"revision\": \"head\",\n1727:       \"path\": \"spirent/vstc/docker/Dockerfile\",\n1728:       \"bytes\": 115,\n1729:       \"lines\": 7\n1730:     },\n1731:     {\n1732:       \"revision\": \"head\",\n1733:       \"path\": \"spirent/vstc/docker/launch.py\",\n1734:       \"bytes\": 4180,\n1735:       \"lines\": 155\n1736:     },\n1737:     {\n1738:       \"revision\": \"head\",\n1739:       \"path\": \"spirent/vstc/Makefile\",\n1740:       \"bytes\": 211,\n1741:       \"lines\": 9\n1742:     },\n1743:     {\n1744:       \"revision\": \"head\",\n1745:       \"path\": \"spirent/vstc/README.md\",\n1746:       \"bytes\": 950,\n1747:       \"lines\": 33\n1748:     },\n1749:     {\n1750:       \"revision\": \"head\",\n1751:       \"path\": \"truenas/truenas/docker/Dockerfile\",\n1752:       \"bytes\": 294,\n1753:       \"lines\": 11\n1754:     },\n1755:     {\n1756:       \"revision\": \"head\",\n1757:       \"path\": \"truenas/truenas/docker/launch.py\",\n1758:       \"bytes\": 21099,\n1759:       \"lines\": 487\n1760:     },\n1761:     {\n1762:       \"revision\": \"head\",\n1763:       \"path\": \"truenas/truenas/docker/tnrpc.py\",\n1764:       \"bytes\": 5570,\n1765:       \"lines\": 151\n1766:     },\n1767:     {\n1768:       \"revision\": \"head\",\n1769:       \"path\": \"truenas/truenas/Makefile\",\n1770:       \"bytes\": 947,\n1771:       \"lines\": 26\n1772:     },\n1773:     {\n1774:       \"revision\": \"head\",\n1775:       \"path\": \"truenas/truenas/README.md\",\n1776:       \"bytes\": 5227,\n1777:       \"lines\": 119\n1778:     },\n1779:     {\n1780:       \"revision\": \"head\",\n1781:       \"path\": \"ubuntu/docker/Dockerfile\",\n1782:       \"bytes\": 412,\n1783:       \"lines\": 21\n1784:     },\n1785:     {\n1786:       \"revision\": \"head\",\n1787:       \"path\": \"ubuntu/docker/launch.py\",\n1788:       \"bytes\": 6754,\n1789:       \"lines\": 216\n1790:     },\n1791:     {\n1792:       \"revision\": \"head\",\n1793:       \"path\": \"ubuntu/download.sh\",\n1794:       \"bytes\": 512,\n1795:       \"lines\": 18\n1796:     },\n1797:     {\n1798:       \"revision\": \"head\",\n1799:       \"path\": \"ubuntu/Makefile\",\n1800:       \"bytes\": 332,\n1801:       \"lines\": 18\n1802:     },\n1803:     {\n1804:       \"revision\": \"head\",\n1805:       \"path\": \"ubuntu/README.md\",\n1806:       \"bytes\": 663,\n1807:       \"lines\": 21\n1808:     },\n1809:     {\n1810:       \"revision\": \"head\",\n1811:       \"path\": \"uv.lock\",\n1812:       \"bytes\": 6571,\n1813:       \"lines\": 95\n1814:     },\n1815:     {\n1816:       \"revision\": \"head\",\n1817:       \"path\": \"vrnetlab-base.dockerfile\",\n1818:       \"bytes\": 882,\n1819:       \"lines\": 41\n1820:     },\n1821:     {\n1822:       \"revision\": \"base\",\n1823:       \"path\": \"fortinet/common/cli_commands.py\",\n1824:       \"bytes\": 5602,\n1825:       \"lines\": 185\n1826:     },\n1827:     {\n1828:       \"revision\": \"base\",\n1829:       \"path\": \"fortinet/common/common.py\",\n1830:       \"bytes\": 3506,\n1831:       \"lines\": 87\n1832:     },\n1833:     {\n1834:       \"revision\": \"base\",\n1835:       \"path\": \"fortinet/common/features/base.py\",\n1836:       \"bytes\": 3138,\n1837:       \"lines\": 115\n1838:     },\n1839:     {\n1840:       \"revision\": \"base\",\n1841:       \"path\": \"fortinet/common/features/credentials.py\",\n1842:       \"bytes\": 2752,\n1843:       \"lines\": 64\n1844:     },\n1845:     {\n1846:       \"revision\": \"base\",\n1847:       \"path\": \"fortinet/common/features/pki.py\",\n1848:       \"bytes\": 17545,\n1849:       \"lines\": 470\n1850:     },\n1851:     {\n1852:       \"revision\": \"base\",\n1853:       \"path\": \"fortinet/common/features/startup_config.py\",\n1854:       \"bytes\": 2989,\n1855:       \"lines\": 80\n1856:     },\n1857:     {\n1858:       \"revision\": \"base\",\n1859:       \"path\": \"fortinet/common/fos_cli_driver.py\",\n1860:       \"bytes\": 12828,\n1861:       \"lines\": 319\n1862:     },\n1863:     {\n1864:       \"revision\": \"base\",\n1865:       \"path\": \"fortinet/common/fos_commander.py\",\n1866:       \"bytes\": 20149,\n1867:       \"lines\": 511\n1868:     },\n1869:     {\n1870:       \"revision\": \"base\",\n1871:       \"path\": \"fortinet/common/launch.py\",\n1872:       \"bytes\": 18364,\n1873:       \"lines\": 503\n1874:     },\n1875:     {\n1876:       \"revision\": \"base\",\n1877:       \"path\": \"fortinet/common/terminal.py\",\n1878:       \"bytes\": 12545,\n1879:       \"lines\": 382\n1880:     },\n1881:     {\n1882:       \"revision\": \"base\",\n1883:       \"path\": \"fortinet/fortigate/docker/README.md\",\n1884:       \"bytes\": 22149,\n1885:       \"lines\": 469\n1886:     },\n1887:     {\n1888:       \"revision\": \"base\",\n1889:       \"path\": \"fortinet/fortigate/README.md\",\n1890:       \"bytes\": 24956,\n1891:       \"lines\": 493\n1892:     },\n1893:     {\n1894:       \"revision\": \"base\",\n1895:       \"path\": \"fortinet/tests/test_common_stack_boundaries.py\",\n1896:       \"bytes\": 15060,\n1897:       \"lines\": 343\n1898:     },\n1899:     {\n1900:       \"revision\": \"base\",\n1901:       \"path\": \"fortinet/tests/test_common_stack_parsing.py\",\n1902:       \"bytes\": 7182,\n1903:       \"lines\": 191\n1904:     },\n1905:     {\n1906:       \"revision\": \"base\",\n1907:       \"path\": \"fortinet/tests/test_common_terminal_driver.py\",\n1908:       \"bytes\": 10230,\n1909:       \"lines\": 226\n1910:     },\n1911:     {\n1912:       \"revision\": \"base\",\n1913:       \"path\": \".deepsource.toml\",\n1914:       \"bytes\": 106,\n1915:       \"lines\": 8\n1916:     },\n1917:     {\n1918:       \"revision\": \"base\",\n1919:       \"path\": \".env\",\n1920:       \"bytes\": 23,\n1921:       \"lines\": 1\n1922:     },\n1923:     {\n1924:       \"revision\": \"base\",\n1925:       \"path\": \".github/workflows/tofarev.yml\",\n1926:       \"bytes\": 1071,\n1927:       \"lines\": 25\n1928:     },\n1929:     {\n1930:       \"revision\": \"base\",\n1931:       \"path\": \".gitignore\",\n1932:       \"bytes\": 444,\n1933:       \"lines\": 35\n1934:     },\n1935:     {\n1936:       \"revision\": \"base\",\n1937:       \"path\": \".gitlab-ci.yml\",\n1938:       \"bytes\": 1047,\n1939:       \"lines\": 22\n1940:     },\n1941:     {\n1942:       \"revision\": \"base\",\n1943:       \"path\": \"arista/veos/docker/Dockerfile\",\n1944:       \"bytes\": 255,\n1945:       \"lines\": 9\n1946:     },\n1947:     {\n1948:       \"revision\": \"base\",\n1949:       \"path\": \"arista/veos/docker/launch.py\",\n1950:       \"bytes\": 6224,\n1951:       \"lines\": 194\n1952:     },\n1953:     {\n1954:       \"revision\": \"base\",\n1955:       \"path\": \"arista/veos/Makefile\",\n1956:       \"bytes\": 1034,\n1957:       \"lines\": 25\n1958:     },\n1959:     {\n1960:       \"revision\": \"base\",\n1961:       \"path\": \"arista/veos/README.md\",\n1962:       \"bytes\": 1281,\n1963:       \"lines\": 36\n1964:     },\n1965:     {\n1966:       \"revision\": \"base\",\n1967:       \"path\": \"arrcus/arcos/docker/Dockerfile\",\n1968:       \"bytes\": 120,\n1969:       \"lines\": 7\n1970:     },\n1971:     {\n1972:       \"revision\": \"base\",\n1973:       \"path\": \"arrcus/arcos/docker/launch.py\",\n1974:       \"bytes\": 13701,\n1975:       \"lines\": 370\n1976:     },\n1977:     {\n1978:       \"revision\": \"base\",\n1979:       \"path\": \"arrcus/arcos/Makefile\",\n1980:       \"bytes\": 286,\n1981:       \"lines\": 11\n1982:     },\n1983:     {\n1984:       \"revision\": \"base\",\n1985:       \"path\": \"arrcus/arcos/README.md\",\n1986:       \"bytes\": 1724,\n1987:       \"lines\": 61\n1988:     },\n1989:     {\n1990:       \"revision\": \"base\",\n1991:       \"path\": \"arrcus/arcos/smoke-test.sh\",\n1992:       \"bytes\": 2983,\n1993:       \"lines\": 105\n1994:     },\n1995:     {\n1996:       \"revision\": \"base\",\n1997:       \"path\": \"aruba/aoscx/docker/Dockerfile\",\n1998:       \"bytes\": 322,\n1999:       \"lines\": 14\n2000:     },\n\n(Showing lines 1-2000 of 3553. Use offset=2001 to continue.)\n</content>",
    "title": "source/manifest.json",
    "metadata": {
      "preview": "{\n  \"version\": 1,\n  \"head\": \"1c29a33a37619b7547248e3b845130ba1f5f8ad0\",\n  \"base\": \"11dd16f88e2e5990de1061be498577af6c5d3552\",\n  \"mergeBase\": \"11dd16f88e2e5990de1061be498577af6c5d3552\",\n  \"changed\": [\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/cli_commands.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/common.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/features/base.py\"\n    },\n    {\n      \"status\": \"M\",",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/manifest.json",
        "text": "{\n  \"version\": 1,\n  \"head\": \"1c29a33a37619b7547248e3b845130ba1f5f8ad0\",\n  \"base\": \"11dd16f88e2e5990de1061be498577af6c5d3552\",\n  \"mergeBase\": \"11dd16f88e2e5990de1061be498577af6c5d3552\",\n  \"changed\": [\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/cli_commands.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/common.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/features/base.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/features/credentials.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/features/pki.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/features/startup_config.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/fos_cli_driver.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/fos_commander.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/launch.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/common/terminal.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/fortigate/README.md\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/fortigate/docker/README.md\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"fortinet/tests/test_common_admin_credentials.py\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"fortinet/tests/test_common_recovery.py\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"fortinet/tests/test_common_scope_errors.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/tests/test_common_stack_boundaries.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/tests/test_common_stack_parsing.py\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"fortinet/tests/test_common_terminal_driver.py\"\n    }\n  ],\n  \"files\": [\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/cli_commands.py\",\n      \"bytes\": 6467,\n      \"lines\": 207\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/common.py\",\n      \"bytes\": 3700,\n      \"lines\": 92\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/base.py\",\n      \"bytes\": 3298,\n      \"lines\": 119\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/credentials.py\",\n      \"bytes\": 4094,\n      \"lines\": 90\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/pki.py\",\n      \"bytes\": 17660,\n      \"lines\": 471\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/startup_config.py\",\n      \"bytes\": 4247,\n      \"lines\": 117\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/fos_cli_driver.py\",\n      \"bytes\": 13311,\n      \"lines\": 331\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/fos_commander.py\",\n      \"bytes\": 27921,\n      \"lines\": 687\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/launch.py\",\n      \"bytes\": 18457,\n      \"lines\": 506\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/terminal.py\",\n      \"bytes\": 13228,\n      \"lines\": 398\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortigate/docker/README.md\",\n      \"bytes\": 24337,\n      \"lines\": 500\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortigate/README.md\",\n      \"bytes\": 25304,\n      \"lines\": 497\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_admin_credentials.py\",\n      \"bytes\": 6689,\n      \"lines\": 154\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_recovery.py\",\n      \"bytes\": 13626,\n      \"lines\": 292\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_scope_errors.py\",\n      \"bytes\": 7676,\n      \"lines\": 154\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_stack_boundaries.py\",\n      \"bytes\": 15421,\n      \"lines\": 349\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_stack_parsing.py\",\n      \"bytes\": 10427,\n      \"lines\": 268\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_terminal_driver.py\",\n      \"bytes\": 15190,\n      \"lines\": 332\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".deepsource.toml\",\n      \"bytes\": 106,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".env\",\n      \"bytes\": 23,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".github/workflows/tofarev.yml\",\n      \"bytes\": 1071,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".gitignore\",\n      \"bytes\": 444,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \".gitlab-ci.yml\",\n      \"bytes\": 1047,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arista/veos/docker/Dockerfile\",\n      \"bytes\": 255,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arista/veos/docker/launch.py\",\n      \"bytes\": 6224,\n      \"lines\": 194\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arista/veos/Makefile\",\n      \"bytes\": 1034,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arista/veos/README.md\",\n      \"bytes\": 1281,\n      \"lines\": 36\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arrcus/arcos/docker/Dockerfile\",\n      \"bytes\": 120,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arrcus/arcos/docker/launch.py\",\n      \"bytes\": 13701,\n      \"lines\": 370\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arrcus/arcos/Makefile\",\n      \"bytes\": 286,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arrcus/arcos/README.md\",\n      \"bytes\": 1724,\n      \"lines\": 61\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"arrcus/arcos/smoke-test.sh\",\n      \"bytes\": 2983,\n      \"lines\": 105\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"aruba/aoscx/docker/Dockerfile\",\n      \"bytes\": 322,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"aruba/aoscx/docker/launch.py\",\n      \"bytes\": 6223,\n      \"lines\": 189\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"aruba/aoscx/Makefile\",\n      \"bytes\": 316,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"aruba/aoscx/README.md\",\n      \"bytes\": 1031,\n      \"lines\": 28\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"build-base-image.sh\",\n      \"bytes\": 300,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/asav/docker/Dockerfile\",\n      \"bytes\": 80,\n      \"lines\": 5\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/asav/docker/launch.py\",\n      \"bytes\": 8663,\n      \"lines\": 268\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/asav/Makefile\",\n      \"bytes\": 249,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/asav/README.md\",\n      \"bytes\": 2133,\n      \"lines\": 68\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/c8000v/docker/Dockerfile\",\n      \"bytes\": 193,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/c8000v/docker/launch.py\",\n      \"bytes\": 16574,\n      \"lines\": 480\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/c8000v/Makefile\",\n      \"bytes\": 2178,\n      \"lines\": 51\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/c8000v/README.md\",\n      \"bytes\": 8825,\n      \"lines\": 222\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/cat9kv/docker/Dockerfile\",\n      \"bytes\": 298,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/cat9kv/docker/launch.py\",\n      \"bytes\": 8036,\n      \"lines\": 270\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/cat9kv/Makefile\",\n      \"bytes\": 460,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/cat9kv/README.md\",\n      \"bytes\": 4101,\n      \"lines\": 119\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/csr1000v/docker/Dockerfile\",\n      \"bytes\": 155,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/csr1000v/docker/launch.py\",\n      \"bytes\": 8713,\n      \"lines\": 314\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/csr1000v/Makefile\",\n      \"bytes\": 721,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/csr1000v/README.md\",\n      \"bytes\": 3441,\n      \"lines\": 78\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/ftdv/docker/Dockerfile\",\n      \"bytes\": 129,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/ftdv/docker/launch.py\",\n      \"bytes\": 11036,\n      \"lines\": 324\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/ftdv/Makefile\",\n      \"bytes\": 352,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/ftdv/README.md\",\n      \"bytes\": 1393,\n      \"lines\": 46\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/iol/docker/Dockerfile\",\n      \"bytes\": 903,\n      \"lines\": 37\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/iol/docker/entrypoint.sh\",\n      \"bytes\": 90,\n      \"lines\": 3\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/iol/Makefile\",\n      \"bytes\": 2312,\n      \"lines\": 55\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/iol/README.md\",\n      \"bytes\": 2779,\n      \"lines\": 66\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/n9kv/docker/Dockerfile\",\n      \"bytes\": 196,\n      \"lines\": 10\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/n9kv/docker/launch.py\",\n      \"bytes\": 7707,\n      \"lines\": 248\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/n9kv/Makefile\",\n      \"bytes\": 368,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/n9kv/README.md\",\n      \"bytes\": 1251,\n      \"lines\": 45\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/nxos/docker/Dockerfile\",\n      \"bytes\": 120,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/nxos/docker/launch.py\",\n      \"bytes\": 5944,\n      \"lines\": 203\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/nxos/Makefile\",\n      \"bytes\": 371,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/nxos/README.md\",\n      \"bytes\": 1181,\n      \"lines\": 37\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/docker/Dockerfile\",\n      \"bytes\": 442,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/docker/launch.py\",\n      \"bytes\": 10580,\n      \"lines\": 329\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/docker/templates/controller-zcloud.xml.j2\",\n      \"bytes\": 1542,\n      \"lines\": 59\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/docker/templates/manager-zcloud.xml.j2\",\n      \"bytes\": 1544,\n      \"lines\": 59\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/docker/templates/validator-zcloud.xml.j2\",\n      \"bytes\": 1574,\n      \"lines\": 62\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/Makefile\",\n      \"bytes\": 2260,\n      \"lines\": 44\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/sdwan-components/README.md\",\n      \"bytes\": 1908,\n      \"lines\": 91\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/vios/docker/Dockerfile\",\n      \"bytes\": 116,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/vios/docker/launch.py\",\n      \"bytes\": 7023,\n      \"lines\": 221\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/vios/Makefile\",\n      \"bytes\": 509,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/vios/README.md\",\n      \"bytes\": 4730,\n      \"lines\": 143\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/cloud-init-disable-net.cfg\",\n      \"bytes\": 28,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/Dockerfile\",\n      \"bytes\": 402,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/guest-init.sh\",\n      \"bytes\": 5708,\n      \"lines\": 122\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/launch.py\",\n      \"bytes\": 10326,\n      \"lines\": 266\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/make-golden.sh\",\n      \"bytes\": 5404,\n      \"lines\": 139\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/netplan-mgmt.yaml\",\n      \"bytes\": 457,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/xrd-guest-init.service\",\n      \"bytes\": 261,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/docker/xrd-unconfined\",\n      \"bytes\": 274,\n      \"lines\": 16\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/Makefile\",\n      \"bytes\": 1286,\n      \"lines\": 33\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrd-vrouter/README.md\",\n      \"bytes\": 4702,\n      \"lines\": 79\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv/docker/Dockerfile\",\n      \"bytes\": 126,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv/docker/launch.py\",\n      \"bytes\": 7862,\n      \"lines\": 259\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv/Makefile\",\n      \"bytes\": 910,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv/README.md\",\n      \"bytes\": 1498,\n      \"lines\": 29\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv9k/docker/Dockerfile\",\n      \"bytes\": 148,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv9k/docker/launch.py\",\n      \"bytes\": 13568,\n      \"lines\": 426\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv9k/LICENSE\",\n      \"bytes\": 1109,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv9k/Makefile\",\n      \"bytes\": 561,\n      \"lines\": 23\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"cisco/xrv9k/README.md\",\n      \"bytes\": 2699,\n      \"lines\": 63\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"CODE_OF_CONDUCT.md\",\n      \"bytes\": 95,\n      \"lines\": 3\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"common/healthcheck.py\",\n      \"bytes\": 339,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"common/vrnetlab.py\",\n      \"bytes\": 64326,\n      \"lines\": 1716\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"CONTRIBUTING.md\",\n      \"bytes\": 709,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/dell_sonic/docker/backup.sh\",\n      \"bytes\": 2833,\n      \"lines\": 107\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/dell_sonic/docker/Dockerfile\",\n      \"bytes\": 122,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/dell_sonic/docker/launch.py\",\n      \"bytes\": 5835,\n      \"lines\": 185\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/dell_sonic/Makefile\",\n      \"bytes\": 380,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/dell_sonic/README.md\",\n      \"bytes\": 1030,\n      \"lines\": 23\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/ftosv/docker/Dockerfile\",\n      \"bytes\": 309,\n      \"lines\": 10\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/ftosv/docker/launch.py\",\n      \"bytes\": 8356,\n      \"lines\": 230\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/ftosv/Makefile\",\n      \"bytes\": 287,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dell/ftosv/README.md\",\n      \"bytes\": 17648,\n      \"lines\": 235\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"dev-notes.md\",\n      \"bytes\": 352,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/exos/docker/Dockerfile\",\n      \"bytes\": 80,\n      \"lines\": 5\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/exos/docker/launch.py\",\n      \"bytes\": 7926,\n      \"lines\": 219\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/exos/Makefile\",\n      \"bytes\": 261,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/exos/README.md\",\n      \"bytes\": 1735,\n      \"lines\": 42\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/voss/docker/Dockerfile\",\n      \"bytes\": 80,\n      \"lines\": 5\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/voss/docker/launch.py\",\n      \"bytes\": 9114,\n      \"lines\": 245\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/voss/Makefile\",\n      \"bytes\": 296,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"extreme/voss/README.md\",\n      \"bytes\": 790,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"f5_bigip/docker/Dockerfile\",\n      \"bytes\": 229,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"f5_bigip/docker/launch.py\",\n      \"bytes\": 16156,\n      \"lines\": 474\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"f5_bigip/Makefile\",\n      \"bytes\": 529,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"f5_bigip/README.md\",\n      \"bytes\": 1273,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/__init__.py\",\n      \"bytes\": 66,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/config_diff.py\",\n      \"bytes\": 4069,\n      \"lines\": 138\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/env.py\",\n      \"bytes\": 1523,\n      \"lines\": 48\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/__init__.py\",\n      \"bytes\": 1534,\n      \"lines\": 49\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/capture_config.py\",\n      \"bytes\": 14172,\n      \"lines\": 362\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/default_config.py\",\n      \"bytes\": 1077,\n      \"lines\": 33\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/disks.py\",\n      \"bytes\": 3193,\n      \"lines\": 86\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/fortiguard_hooks.py\",\n      \"bytes\": 3440,\n      \"lines\": 103\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/fortitoken.py\",\n      \"bytes\": 2951,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/image_info.py\",\n      \"bytes\": 2616,\n      \"lines\": 81\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/license.py\",\n      \"bytes\": 10131,\n      \"lines\": 268\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/mgmt_dns.py\",\n      \"bytes\": 2139,\n      \"lines\": 60\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/mgmt_net.py\",\n      \"bytes\": 4174,\n      \"lines\": 114\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/features/product.py\",\n      \"bytes\": 3918,\n      \"lines\": 107\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/file_watcher.py\",\n      \"bytes\": 2307,\n      \"lines\": 69\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/fos_healthcheck.py\",\n      \"bytes\": 3984,\n      \"lines\": 111\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/host_forwarded_bridge.py\",\n      \"bytes\": 3614,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/net_mgmt_strategy.py\",\n      \"bytes\": 1299,\n      \"lines\": 48\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/passthrough_redirect.py\",\n      \"bytes\": 8909,\n      \"lines\": 201\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/common/tftp.py\",\n      \"bytes\": 2742,\n      \"lines\": 88\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortigate/.gitignore\",\n      \"bytes\": 7,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortigate/docker/Dockerfile\",\n      \"bytes\": 1146,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortigate/docker/launch.py\",\n      \"bytes\": 106,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortigate/Makefile\",\n      \"bytes\": 1146,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortiproxy/.gitignore\",\n      \"bytes\": 8,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortiproxy/docker/Dockerfile\",\n      \"bytes\": 418,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortiproxy/docker/launch.py\",\n      \"bytes\": 107,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortiproxy/docker/README.md\",\n      \"bytes\": 189,\n      \"lines\": 4\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortiproxy/Makefile\",\n      \"bytes\": 1156,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/fortiproxy/README.md\",\n      \"bytes\": 1044,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_capture_pki.py\",\n      \"bytes\": 12387,\n      \"lines\": 239\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_commander_scheduler.py\",\n      \"bytes\": 9852,\n      \"lines\": 183\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_commands.py\",\n      \"bytes\": 5500,\n      \"lines\": 137\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_environment_watchers.py\",\n      \"bytes\": 5635,\n      \"lines\": 122\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_features.py\",\n      \"bytes\": 17522,\n      \"lines\": 346\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_license.py\",\n      \"bytes\": 9565,\n      \"lines\": 180\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_common_network_launch.py\",\n      \"bytes\": 12810,\n      \"lines\": 239\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_fos_commander.py\",\n      \"bytes\": 3608,\n      \"lines\": 93\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"fortinet/tests/test_vrnetlab.py\",\n      \"bytes\": 4478,\n      \"lines\": 127\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"freebsd/docker/backup.sh\",\n      \"bytes\": 2071,\n      \"lines\": 84\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"freebsd/docker/Dockerfile\",\n      \"bytes\": 442,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"freebsd/docker/launch.py\",\n      \"bytes\": 8117,\n      \"lines\": 257\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"freebsd/download.sh\",\n      \"bytes\": 682,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"freebsd/Makefile\",\n      \"bytes\": 342,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"freebsd/README.md\",\n      \"bytes\": 1714,\n      \"lines\": 52\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"hp/vsr1000/docker/Dockerfile\",\n      \"bytes\": 187,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"hp/vsr1000/docker/launch.py\",\n      \"bytes\": 5525,\n      \"lines\": 160\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"hp/vsr1000/Makefile\",\n      \"bytes\": 342,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"hp/vsr1000/README.md\",\n      \"bytes\": 1049,\n      \"lines\": 34\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"huawei/huawei_vrp/docker/Dockerfile\",\n      \"bytes\": 133,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"huawei/huawei_vrp/docker/launch.py\",\n      \"bytes\": 18313,\n      \"lines\": 468\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"huawei/huawei_vrp/Makefile\",\n      \"bytes\": 334,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"huawei/huawei_vrp/README.md\",\n      \"bytes\": 426,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ipinfusion/ocnos/docker/Dockerfile\",\n      \"bytes\": 127,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ipinfusion/ocnos/docker/launch.py\",\n      \"bytes\": 7658,\n      \"lines\": 223\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ipinfusion/ocnos/Makefile\",\n      \"bytes\": 522,\n      \"lines\": 16\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ipinfusion/ocnos/README.md\",\n      \"bytes\": 1417,\n      \"lines\": 49\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/apstra/docker/Dockerfile\",\n      \"bytes\": 369,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/apstra/docker/launch.py\",\n      \"bytes\": 10481,\n      \"lines\": 262\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/apstra/Makefile\",\n      \"bytes\": 1225,\n      \"lines\": 36\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/apstra/README.md\",\n      \"bytes\": 10010,\n      \"lines\": 307\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosevolved/docker/Dockerfile\",\n      \"bytes\": 325,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosevolved/docker/init.conf\",\n      \"bytes\": 855,\n      \"lines\": 44\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosevolved/docker/launch.py\",\n      \"bytes\": 8866,\n      \"lines\": 246\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosevolved/docker/make-config.sh\",\n      \"bytes\": 1402,\n      \"lines\": 60\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosevolved/Makefile\",\n      \"bytes\": 352,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosevolved/README.md\",\n      \"bytes\": 718,\n      \"lines\": 19\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosrouter/docker/Dockerfile\",\n      \"bytes\": 325,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosrouter/docker/init.conf\",\n      \"bytes\": 915,\n      \"lines\": 51\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosrouter/docker/launch.py\",\n      \"bytes\": 7341,\n      \"lines\": 212\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosrouter/docker/make-config.sh\",\n      \"bytes\": 1402,\n      \"lines\": 60\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosrouter/Makefile\",\n      \"bytes\": 824,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosrouter/README.md\",\n      \"bytes\": 494,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosswitch/docker/Dockerfile\",\n      \"bytes\": 325,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosswitch/docker/init.conf\",\n      \"bytes\": 915,\n      \"lines\": 51\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosswitch/docker/launch.py\",\n      \"bytes\": 7358,\n      \"lines\": 212\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosswitch/docker/make-config.sh\",\n      \"bytes\": 1402,\n      \"lines\": 60\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosswitch/Makefile\",\n      \"bytes\": 886,\n      \"lines\": 34\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vjunosswitch/README.md\",\n      \"bytes\": 513,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vmx/docker/Dockerfile\",\n      \"bytes\": 295,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vmx/docker/launch.py\",\n      \"bytes\": 17750,\n      \"lines\": 496\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vmx/Makefile\",\n      \"bytes\": 590,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vmx/README.md\",\n      \"bytes\": 1880,\n      \"lines\": 45\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vmx/vmx-extract.sh\",\n      \"bytes\": 894,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vqfx/docker/Dockerfile\",\n      \"bytes\": 328,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vqfx/docker/launch.py\",\n      \"bytes\": 10990,\n      \"lines\": 305\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vqfx/Makefile\",\n      \"bytes\": 2052,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vqfx/README.md\",\n      \"bytes\": 161,\n      \"lines\": 6\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vsrx/docker/Dockerfile\",\n      \"bytes\": 240,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vsrx/docker/init.conf\",\n      \"bytes\": 848,\n      \"lines\": 43\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vsrx/docker/launch.py\",\n      \"bytes\": 6670,\n      \"lines\": 193\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vsrx/docker/make-config-iso.sh\",\n      \"bytes\": 416,\n      \"lines\": 24\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vsrx/Makefile\",\n      \"bytes\": 303,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"juniper/vsrx/README.md\",\n      \"bytes\": 1416,\n      \"lines\": 29\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"LICENSE\",\n      \"bytes\": 1109,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"makefile-install.include\",\n      \"bytes\": 3279,\n      \"lines\": 48\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"makefile-sanity.include\",\n      \"bytes\": 370,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"makefile.include\",\n      \"bytes\": 3274,\n      \"lines\": 85\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"mikrotik/routeros/docker/Dockerfile\",\n      \"bytes\": 350,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"mikrotik/routeros/docker/launch.py\",\n      \"bytes\": 11967,\n      \"lines\": 313\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"mikrotik/routeros/Makefile\",\n      \"bytes\": 1687,\n      \"lines\": 39\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"mikrotik/routeros/README.md\",\n      \"bytes\": 998,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"netapp/ontap/docker/Dockerfile\",\n      \"bytes\": 724,\n      \"lines\": 26\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"netapp/ontap/docker/launch.py\",\n      \"bytes\": 22293,\n      \"lines\": 521\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"netapp/ontap/Makefile\",\n      \"bytes\": 337,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"netapp/ontap/README.md\",\n      \"bytes\": 7014,\n      \"lines\": 171\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/cmglinux/docker/Dockerfile\",\n      \"bytes\": 412,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/cmglinux/docker/launch.py\",\n      \"bytes\": 9068,\n      \"lines\": 299\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/cmglinux/Makefile\",\n      \"bytes\": 304,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/cmglinux/README.md\",\n      \"bytes\": 2931,\n      \"lines\": 100\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/sros/docker/Dockerfile\",\n      \"bytes\": 152,\n      \"lines\": 6\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/sros/docker/launch.py\",\n      \"bytes\": 72283,\n      \"lines\": 1983\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/sros/Makefile\",\n      \"bytes\": 337,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nokia/sros/README.md\",\n      \"bytes\": 7221,\n      \"lines\": 126\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nvidia/cumulus-vx/docker/Dockerfile\",\n      \"bytes\": 375,\n      \"lines\": 14\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nvidia/cumulus-vx/docker/launch.py\",\n      \"bytes\": 24943,\n      \"lines\": 649\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nvidia/cumulus-vx/Makefile\",\n      \"bytes\": 1250,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"nvidia/cumulus-vx/README.md\",\n      \"bytes\": 2977,\n      \"lines\": 101\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openbsd/docker/backup.sh\",\n      \"bytes\": 2069,\n      \"lines\": 84\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openbsd/docker/Dockerfile\",\n      \"bytes\": 428,\n      \"lines\": 20\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openbsd/docker/launch.py\",\n      \"bytes\": 6854,\n      \"lines\": 218\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openbsd/download.sh\",\n      \"bytes\": 769,\n      \"lines\": 28\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openbsd/Makefile\",\n      \"bytes\": 352,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openbsd/README.md\",\n      \"bytes\": 1769,\n      \"lines\": 52\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openwrt/docker/Dockerfile\",\n      \"bytes\": 152,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openwrt/docker/launch.py\",\n      \"bytes\": 49519,\n      \"lines\": 1288\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openwrt/download.py\",\n      \"bytes\": 2920,\n      \"lines\": 82\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openwrt/Makefile\",\n      \"bytes\": 533,\n      \"lines\": 20\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"openwrt/README.md\",\n      \"bytes\": 5302,\n      \"lines\": 144\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"opnsense/docker/Dockerfile\",\n      \"bytes\": 401,\n      \"lines\": 19\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"opnsense/docker/launch.py\",\n      \"bytes\": 10379,\n      \"lines\": 280\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"opnsense/Makefile\",\n      \"bytes\": 551,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"opnsense/README.md\",\n      \"bytes\": 2391,\n      \"lines\": 70\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"paloalto/pan/docker/Dockerfile\",\n      \"bytes\": 174,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"paloalto/pan/docker/launch.py\",\n      \"bytes\": 13856,\n      \"lines\": 352\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"paloalto/pan/Makefile\",\n      \"bytes\": 288,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"paloalto/pan/README.md\",\n      \"bytes\": 710,\n      \"lines\": 27\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"plvision/plvision_sonic/docker/backup.sh\",\n      \"bytes\": 2833,\n      \"lines\": 107\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"plvision/plvision_sonic/docker/Dockerfile\",\n      \"bytes\": 503,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"plvision/plvision_sonic/docker/launch.py\",\n      \"bytes\": 6323,\n      \"lines\": 189\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"plvision/plvision_sonic/Makefile\",\n      \"bytes\": 458,\n      \"lines\": 13\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"plvision/plvision_sonic/README.md\",\n      \"bytes\": 1506,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"pyproject.toml\",\n      \"bytes\": 417,\n      \"lines\": 17\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"README.md\",\n      \"bytes\": 8444,\n      \"lines\": 169\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"sonic/docker/backup.sh\",\n      \"bytes\": 2833,\n      \"lines\": 107\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"sonic/docker/Dockerfile\",\n      \"bytes\": 415,\n      \"lines\": 15\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"sonic/docker/launch.py\",\n      \"bytes\": 6278,\n      \"lines\": 189\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"sonic/Makefile\",\n      \"bytes\": 269,\n      \"lines\": 12\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"sonic/README.md\",\n      \"bytes\": 1305,\n      \"lines\": 31\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"spirent/vstc/docker/Dockerfile\",\n      \"bytes\": 115,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"spirent/vstc/docker/launch.py\",\n      \"bytes\": 4180,\n      \"lines\": 155\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"spirent/vstc/Makefile\",\n      \"bytes\": 211,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"spirent/vstc/README.md\",\n      \"bytes\": 950,\n      \"lines\": 33\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"truenas/truenas/docker/Dockerfile\",\n      \"bytes\": 294,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"truenas/truenas/docker/launch.py\",\n      \"bytes\": 21099,\n      \"lines\": 487\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"truenas/truenas/docker/tnrpc.py\",\n      \"bytes\": 5570,\n      \"lines\": 151\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"truenas/truenas/Makefile\",\n      \"bytes\": 947,\n      \"lines\": 26\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"truenas/truenas/README.md\",\n      \"bytes\": 5227,\n      \"lines\": 119\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ubuntu/docker/Dockerfile\",\n      \"bytes\": 412,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ubuntu/docker/launch.py\",\n      \"bytes\": 6754,\n      \"lines\": 216\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ubuntu/download.sh\",\n      \"bytes\": 512,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ubuntu/Makefile\",\n      \"bytes\": 332,\n      \"lines\": 18\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"ubuntu/README.md\",\n      \"bytes\": 663,\n      \"lines\": 21\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"uv.lock\",\n      \"bytes\": 6571,\n      \"lines\": 95\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"vrnetlab-base.dockerfile\",\n      \"bytes\": 882,\n      \"lines\": 41\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/cli_commands.py\",\n      \"bytes\": 5602,\n      \"lines\": 185\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/common.py\",\n      \"bytes\": 3506,\n      \"lines\": 87\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/features/base.py\",\n      \"bytes\": 3138,\n      \"lines\": 115\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/features/credentials.py\",\n      \"bytes\": 2752,\n      \"lines\": 64\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/features/pki.py\",\n      \"bytes\": 17545,\n      \"lines\": 470\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/features/startup_config.py\",\n      \"bytes\": 2989,\n      \"lines\": 80\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/fos_cli_driver.py\",\n      \"bytes\": 12828,\n      \"lines\": 319\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/fos_commander.py\",\n      \"bytes\": 20149,\n      \"lines\": 511\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/launch.py\",\n      \"bytes\": 18364,\n      \"lines\": 503\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/common/terminal.py\",\n      \"bytes\": 12545,\n      \"lines\": 382\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/fortigate/docker/README.md\",\n      \"bytes\": 22149,\n      \"lines\": 469\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/fortigate/README.md\",\n      \"bytes\": 24956,\n      \"lines\": 493\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/tests/test_common_stack_boundaries.py\",\n      \"bytes\": 15060,\n      \"lines\": 343\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/tests/test_common_stack_parsing.py\",\n      \"bytes\": 7182,\n      \"lines\": 191\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"fortinet/tests/test_common_terminal_driver.py\",\n      \"bytes\": 10230,\n      \"lines\": 226\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \".deepsource.toml\",\n      \"bytes\": 106,\n      \"lines\": 8\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \".env\",\n      \"bytes\": 23,\n      \"lines\": 1\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \".github/workflows/tofarev.yml\",\n      \"bytes\": 1071,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \".gitignore\",\n      \"bytes\": 444,\n      \"lines\": 35\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \".gitlab-ci.yml\",\n      \"bytes\": 1047,\n      \"lines\": 22\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arista/veos/docker/Dockerfile\",\n      \"bytes\": 255,\n      \"lines\": 9\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arista/veos/docker/launch.py\",\n      \"bytes\": 6224,\n      \"lines\": 194\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arista/veos/Makefile\",\n      \"bytes\": 1034,\n      \"lines\": 25\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arista/veos/README.md\",\n      \"bytes\": 1281,\n      \"lines\": 36\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arrcus/arcos/docker/Dockerfile\",\n      \"bytes\": 120,\n      \"lines\": 7\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arrcus/arcos/docker/launch.py\",\n      \"bytes\": 13701,\n      \"lines\": 370\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arrcus/arcos/Makefile\",\n      \"bytes\": 286,\n      \"lines\": 11\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arrcus/arcos/README.md\",\n      \"bytes\": 1724,\n      \"lines\": 61\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"arrcus/arcos/smoke-test.sh\",\n      \"bytes\": 2983,\n      \"lines\": 105\n    },\n    {\n      \"revision\": \"base\",\n      \"path\": \"aruba/aoscx/docker/Dockerfile\",\n      \"bytes\": 322,\n      \"lines\": 14\n    },",
        "lineStart": 1,
        "lineEnd": 2000,
        "totalLines": 3553,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716198302,
      "end": 1793716198342
    }
  }
}
read · completed

Input

{
  "filePath": "/source/diff.txt"
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py
2: index ea16d0f..1af3f4d 100644
3: --- a/fortinet/common/cli_commands.py
4: +++ b/fortinet/common/cli_commands.py
5: @@ -12,46 +12,72 @@ class SessionLossAction(Enum):
6:      CONTINUE = auto()
7:      VALIDATE = auto()
8:      FAIL = auto()
9:  
10:  
11: +class ContextLossAction(Enum):
12: +    RESTART_BLOCK = auto()
13: +    FAIL = auto()
14: +
15: +
16:  @dataclass(frozen=True, init=False)
17:  class CommandSpec:
18:      line: str
19:      completion_states: tuple = ()
20:      capture_output: bool = False
21:      suppress_output: bool = False
22:      session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK
23:      expected_completion_state: object = None
24:      fail_on_error: bool = False
25: +    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK
26: +    continuation: bool = False
27:  
28:      def __init__(self, line, completion_states=(), capture_output=False,
29:                   suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,
30: -                 expected_completion_state=None, fail_on_error=False):
31: +                 expected_completion_state=None, fail_on_error=False,
32: +                 context_loss=None, continuation=False):
33:          object.__setattr__(self, "line", line)
34:          object.__setattr__(self, "completion_states", completion_states)
35:          object.__setattr__(self, "capture_output", capture_output)
36:          object.__setattr__(self, "suppress_output", suppress_output)
37:          object.__setattr__(self, "session_loss", session_loss)
38:          object.__setattr__(self, "expected_completion_state", expected_completion_state)
39:          object.__setattr__(self, "fail_on_error", fail_on_error)
40: +        object.__setattr__(self, "continuation", continuation)
41: +        if context_loss is None:
42: +            # Commands that must not replay after logout must not replay after
43: +            # an unexpected scope exit either. Features can override this policy.
44: +            context_loss = (
45: +                ContextLossAction.RESTART_BLOCK
46: +                if session_loss == SessionLossAction.RESTART_BLOCK
47: +                else ContextLossAction.FAIL
48: +            )
49: +        object.__setattr__(self, "context_loss", context_loss)
50:          self.__post_init__()
51:  
52:      def __post_init__(self):
53:          if "\r" in self.line or "\n" in self.line:
54:              raise ValueError("CLI commands must contain exactly one line")
55:  
56: +    @property
57: +    def closes_scope(self):
58: +        return not self.continuation and self.line.strip().lower() in {"next", "end"}
59: +
60:  
61:  @dataclass
62:  class CommandAttempt:
63:      spec: CommandSpec
64:      number: int
65:      session_epoch: int
66:      output: bytearray = field(default_factory=bytearray)
67: +    prompt_context_before: tuple | None = None
68: +    prompt_context_after: tuple | None = None
69: +    block_index: int | None = None
70: +    retry_count: int = 0
71:  
72:      def on_output(self, output):
73: -        if not self.spec.capture_output:
74: +        if not (self.spec.capture_output or self.spec.closes_scope):
75:              return False
76:          data = bytes(output)
77:          self.output.extend(data)
78:          output.discard(data)
79:          return True
80: @@ -69,11 +95,11 @@ class Scope:
81:      @property
82:      def close_line(self):
83:          raise NotImplementedError
84:  
85:      def flatten(self):
86: -        commands = [CommandSpec(self.open_line)]
87: +        commands = flatten_commands(self.open_line)
88:          for child in self.children:
89:              commands.extend(flatten_commands(child))
90:          commands.append(CommandSpec(self.close_line))
91:          return commands
92:  
93: @@ -107,49 +133,43 @@ class SetValue:
94:          self.fail_on_error = fail_on_error
95:          self.validate_prompt = validate_prompt
96:  
97:      def flatten(self):
98:          lines = str(self.value).strip().splitlines() or [""]
99: -        if len(lines) == 1:
100: -            return [CommandSpec(
101: -                f'set {self.field} "{lines[0]}"',
102: -                capture_output=True,
103: -                expected_completion_state=(
104: -                    FOSCliState.CMD_PROMPT if self.validate_prompt else None
105: -                ),
106: -                fail_on_error=self.fail_on_error,
107: -            )]
108: -
109: -        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
110: -        commands = [CommandSpec(
111: -            f'set {self.field} "{lines[0]}',
112: -            completion_states=both_prompts,
113: -            capture_output=True,
114: -            expected_completion_state=(
115: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None
116: -            ),
117: -            fail_on_error=self.fail_on_error,
118: -        )]
119: -        commands.extend(CommandSpec(
120: -            line,
121: -            completion_states=both_prompts,
122: -            capture_output=True,
123: -            expected_completion_state=(
124: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None
125: -            ),
126: -            fail_on_error=self.fail_on_error,
127: -        ) for line in lines[1:-1])
128: +        lines[0] = f'set {self.field} "{lines[0]}'
129: +        lines[-1] += '"'
130: +        return _flatten_quoted_lines(
131: +            lines, fail_on_error=self.fail_on_error,
132: +            validate_prompt=self.validate_prompt,
133: +        )
134: +
135: +
136: +def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):
137: +    """Send a logical command one line per continuation prompt, without re-quoting."""
138: +    commands = []
139: +    for index, line in enumerate(lines):
140: +        last_line = index == len(lines) - 1
141: +        expected = (
142: +            FOSCliState.CMD_PROMPT if last_line
143: +            else FOSCliState.MULTILINE_PROMPT
144: +        )
145: +        completion_states = ()
146: +        if len(lines) > 1:
147: +            completion_states = (
148: +                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)
149: +                if last_line else
150: +                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
151: +            )
152:          commands.append(CommandSpec(
153: -            f'{lines[-1]}"',
154: -            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),
155: +            line,
156: +            completion_states=completion_states,
157:              capture_output=True,
158: -            expected_completion_state=(
159: -                FOSCliState.CMD_PROMPT if self.validate_prompt else None
160: -            ),
161: -            fail_on_error=self.fail_on_error,
162: +            expected_completion_state=expected if validate_prompt else None,
163: +            fail_on_error=fail_on_error,
164: +            continuation=index > 0,
165:          ))
166: -        return commands
167: +    return commands
168:  
169:  
170:  class CommandSequence:
171:      """An unscoped workflow container; it does not emit CLI framing."""
172:  
173: @@ -165,10 +185,12 @@ class CommandSequence:
174:  
175:  
176:  def flatten_commands(value):
177:      """Flatten command containers and wrap plain CLI lines with defaults."""
178:      if isinstance(value, str):
179: +        if "\n" in value:
180: +            return _flatten_quoted_lines(value.split("\n"))
181:          return [CommandSpec(value)]
182:      if isinstance(value, CommandSpec):
183:          return [value]
184:      if isinstance(value, (Scope, CommandSequence, SetValue)):
185:          return value.flatten()
186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py
187: index 4ffb817..b020deb 100644
188: --- a/fortinet/common/common.py
189: +++ b/fortinet/common/common.py
190: @@ -21,10 +21,11 @@ class FOSCliState(IntEnum):
191:      CURRENT_PASSWORD = auto()
192:      CONFIRMATION = auto()
193:      CHANGE_PASSWORD_CONFIRM = auto()
194:      MORE_PROMPT = auto()
195:      MULTILINE_PROMPT = auto()
196: +    KERNEL_PANIC = auto()
197:      UNKNOWN = auto()  # Non-patterns from here on.
198:      TN_TIMEOUT = auto()
199:  
200:  
201:  GENERIC_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+"
202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (
203:  )
204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb"(?mi)Do you want to continue\?"
205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb"(?mi)^Confirm Password:[ \t]*"
206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb"--More--\s*"
207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb"(?m)^>[ \t]*\r?$"
208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (
209: +    rb"(?mi)^Kernel panic(?: - not syncing)?:[^\r\n]*\r?\n"
210: +    rb"CPU: [0-9]+ PID: [0-9]+ Comm: [^\r\n]+"
211: +)
212:  
213:  DEF_POLICY_COMPLIANT_PASSWORD = "FortinetFOS1!"
214:  DEFAULT_USERNAME = "admin"
215:  DEFAULT_PASSWORD = DEFAULT_USERNAME
216:  
217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py
218: index 83ebc9b..5dd906a 100644
219: --- a/fortinet/common/features/base.py
220: +++ b/fortinet/common/features/base.py
221: @@ -53,10 +53,14 @@ class Feature:
222:          self.commander.feature_complete(self)
223:  
224:      def on_session_loss(self, attempt):
225:          return attempt.spec.session_loss
226:  
227: +    def on_context_loss(self, attempt):
228: +        """Choose whether the commander may replay this interrupted block."""
229: +        return attempt.spec.context_loss
230: +
231:      def reversal_blocks(self):
232:          """Return command blocks that completely reverse this feature's work."""
233:          return []
234:  
235:      def undo(self):
236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py
237: index b8bc7de..af39225 100644
238: --- a/fortinet/common/features/credentials.py
239: +++ b/fortinet/common/features/credentials.py
240: @@ -1,14 +1,15 @@
241:  """Administrator bootstrap feature."""
242:  
243: -from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction
244: +from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction
245: +from ..common import FOSCliState
246:  
247:  from .base import StaticFeature
248:  
249:  
250:  class CredentialsFeature(StaticFeature):
251: -    """Configure the administrator and change credentials after password loss."""
252: +    """Configure the administrator, then log out and authenticate again."""
253:  
254:      def __init__(self, vm, commander):
255:          self._activate_after_admin_commit = False
256:          self._desired_credentials_activated = False
257:          self._password_change_committed = False
258: @@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):
259:                  fail_on_error=True,
260:              ))
261:          super().__init__(vm, commander, "admin", [
262:              ConfigBlock("system password-policy", ["set status disable"]),
263:              ConfigBlock("system admin", [EditBlock(credentials.username, admin_children)]),
264: +            CommandSequence("admin-relogin", [CommandSpec(
265: +                "exit",
266: +                session_loss=SessionLossAction.CONTINUE,
267: +                capture_output=True,
268: +                fail_on_error=True,
269: +                # A successful logout takes the session-loss path. Returning
270: +                # straight to a CLI prompt must not count as verification.
271: +                expected_completion_state=FOSCliState.PROVIDE_USERNAME,
272: +            )]),
273:          ], on_complete=lambda: self._activate_desired_credentials())
274:  
275: +    def on_command_dispatched(self, attempt):
276: +        if attempt.spec.line == "exit":
277: +            self._activate_desired_credentials()
278: +        super().on_command_dispatched(attempt)
279: +
280:      def on_session_loss(self, attempt):
281: +        if attempt.spec.line == "exit":
282: +            # The commander resumes this block only at the authenticated CLI
283: +            # prompt. Clear the logout command so it cannot be replayed.
284: +            return SessionLossAction.CONTINUE
285:          if self._is_password_command(attempt.spec.line):
286:              self._activate_desired_credentials()
287:              self._activate_after_admin_commit = False
288:              return SessionLossAction.CONTINUE
289: +        if self._activate_after_admin_commit and attempt.spec.line == "next":
290: +            # Some releases log out during the commit instead of returning
291: +            # its CLI prompt. Authenticate with the committed password.
292: +            self._activate_desired_credentials()
293: +            self._activate_after_admin_commit = False
294: +            self._password_change_committed = True
295: +            return SessionLossAction.CONTINUE
296:          if self._password_change_committed:
297:              # FortiOS may log out as the admin edit closes. The password
298:              # command and `next` have already committed the new credentials,
299:              # so replaying this block would use the previous password again.
300:              return SessionLossAction.CONTINUE
301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py
302: index 96a90d3..a5f0de7 100644
303: --- a/fortinet/common/features/pki.py
304: +++ b/fortinet/common/features/pki.py
305: @@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):
306:      @staticmethod
307:      def _config_item_block(scope, name, children):
308:          # A configuration attempt is deliberately best-effort: the feature
309:          # must be able to inspect the result and fall back to the TFTP import
310:          # path when a firmware release does not expose this config tree.  If
311: -        # these wrapper commands keep ``fail_on_error`` enabled, the commander
312: -        # raises before ``on_command_executed`` can record the failed config
313: -        # attempt and select the fallback.
314: +        # opening commands keep ``fail_on_error`` enabled, the commander raises
315: +        # before ``on_command_executed`` can select that fallback. A return-code
316: +        # failure from `next` or `end` is always fatal to the feature: the
317: +        # commander checks scope commits even when fail_on_error is disabled.
318:          def config_command(line):
319:              return CommandSpec(line, capture_output=True, fail_on_error=False)
320:  
321:          return CommandSequence(f"{scope}-{name}", [
322:              config_command(f"config {scope}"),
323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py
324: index e404fc8..cb99aa4 100644
325: --- a/fortinet/common/features/startup_config.py
326: +++ b/fortinet/common/features/startup_config.py
327: @@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):
328:              "FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL"
329:          )
330:      return filtered
331:  
332:  
333: +def _startup_config_commands(config):
334: +    """Yield logical CLI commands while retaining quoted newlines verbatim."""
335: +    pending = []
336: +    quote = None
337: +    start_line = None
338: +    for number, raw_line in enumerate(config, start=1):
339: +        # Text mode normalizes file line endings. Only remove the delimiter;
340: +        # whitespace and comment/scope-looking lines inside quotes are data.
341: +        line = raw_line.removesuffix("\n")
342: +        if not pending:
343: +            line = line.lstrip()
344: +            if not line or line.startswith("#"):
345: +                continue
346: +            start_line = number
347: +
348: +        escaped = False
349: +        for character in line:
350: +            if escaped:
351: +                escaped = False
352: +            elif character == "\\":
353: +                escaped = True
354: +            elif character == quote:
355: +                quote = None
356: +            elif quote is None and character in {"'", '"'}:
357: +                quote = character
358: +
359: +        if quote is not None or escaped:
360: +            pending.append(line)
361: +            continue
362: +        pending.append(line.rstrip())
363: +        yield "\n".join(pending)
364: +        pending.clear()
365: +
366: +    if pending:
367: +        reason = "unterminated quoted string" if quote else "unfinished line continuation"
368: +        raise ValueError(
369: +            f"Startup config malformed. {reason} starting on line {start_line}."
370: +        )
371: +
372: +
373:  def parse_startup_config(path):
374:      roots = []
375:      stack = []
376:      with open(path) as config:
377: -        for raw_line in config:
378: -            line = raw_line.strip()
379: -            if not line or line.startswith("#"):
380: -                continue
381: +        for line in _startup_config_commands(config):
382:              if line.startswith("config "):
383:                  node = ConfigBlock(line[7:])
384:                  (stack[-1].children if stack else roots).append(node)
385:                  stack.append(node)
386:              elif line.startswith("edit "):
387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py
388: index fa34100..b527816 100644
389: --- a/fortinet/common/fos_cli_driver.py
390: +++ b/fortinet/common/fos_cli_driver.py
391: @@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10
392:  EXPECT_TIMEOUT_SECONDS = 1
393:  UNKNOWN_STALL_SECONDS = 30
394:  UNKNOWN_STALL_NEWLINE_LIMIT = 3
395:  
396:  
397: +class KernelPanicError(RuntimeError):
398: +    """Raised when the guest kernel reports a panic on the serial console."""
399: +
400: +
401:  class FOSCliDriver:
402:      """Owns serial reads and delegates command dispatch to the commander."""
403:  
404:      def __init__(
405:          self,
406: @@ -65,10 +69,11 @@ class FOSCliDriver:
407:              FOSCliState.CMD_PROMPT: self._command_prompt,
408:              FOSCliState.CMD_PROMPT_ECHO: None,
409:              FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,
410:              FOSCliState.LIC_FAIL: self._license_failed,
411:              FOSCliState.TN_TIMEOUT: self._timeout,
412: +            FOSCliState.KERNEL_PANIC: self._kernel_panic,
413:              FOSCliState.UNKNOWN: self._unknown,
414:          }
415:  
416:      @property
417:      def state_patterns(self):
418: @@ -145,11 +150,14 @@ class FOSCliDriver:
419:  
420:      def _next_state(self):
421:          index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)
422:          if match:
423:              return FOSCliState(index), output, True
424: -        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False
425: +        # A timeout exposes retained bytes too. Only fresh input should reset
426: +        # the unknown-output stall timer; an unchanged buffer is still idle.
427: +        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT
428: +        return state, output, False
429:  
430:      def _handle_state(self, state):
431:          handler = self._state_handlers.get(state)
432:          if handler:
433:              try:
434: @@ -254,10 +262,14 @@ class FOSCliDriver:
435:  
436:      def _unknown(self):
437:          if self._last_known_state == FOSCliState.REBOOTING:
438:              self._idle_spins += 1
439:  
440: +    @staticmethod
441: +    def _kernel_panic():
442: +        raise KernelPanicError("Kernel panic detected on serial console")
443: +
444:      def _note_unknown_output(self):
445:          self._unknown_started_at = time.monotonic()
446:  
447:      def _recover_unknown_stall(self):
448:          if self._unknown_started_at is None:
449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py
450: index 26312cf..86b1be6 100644
451: --- a/fortinet/common/fos_commander.py
452: +++ b/fortinet/common/fos_commander.py
453: @@ -10,24 +10,29 @@ from .cli_commands import (
454:      CleanupAction,
455:      CommandAttempt,
456:      CommandSequence,
457:      CommandSpec,
458:      ConfigBlock,
459: +    ContextLossAction,
460:      SessionLossAction,
461:      flatten_commands,
462:  )
463:  from .terminal import Data
464: -from .common import FOSCliState, TRACE_LEVEL
465: +from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL
466:  
467:  DISPATCHABLE_COMPLETION_STATES = {
468:      FOSCliState.CMD_PROMPT,
469:      FOSCliState.CONFIRMATION,
470:      FOSCliState.MULTILINE_PROMPT,
471:  }
472:  COMMAND_FAILURE_PATTERN = re.compile(
473:      rb"(?mi)^\s*Command fail\.\s*Return code\s+(-?\d+)"
474:  )
475: +CLI_PROMPT_CONTEXT_PATTERN = re.compile(
476: +    rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX
477: +    + rb"(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$"
478: +)
479:  
480:  
481:  @dataclass
482:  class _StandardOutputContext:
483:      feature: object
484: @@ -35,10 +40,11 @@ class _StandardOutputContext:
485:      phase: str = "inspect"
486:      restore: bool = False
487:  
488:  
489:  class FOSCommander:
490: +    MAX_COMMAND_RECOVERY_RETRIES = 1
491:      _CONSOLE_OUTPUT_PATTERN = re.compile(rb"(?mi)^\s*set output (more|standard)\s*\r?$")
492:      _CONSOLE_INSPECT_LINE = "show full-configuration system console"
493:      _CONSOLE_STANDARD_LINE = "set output standard"
494:  
495:      def __init__(self, terminal, logger, continue_on_error=False):
496: @@ -65,23 +71,37 @@ class FOSCommander:
497:          self._start_time = datetime.datetime.now()
498:          self._continue_on_error = continue_on_error
499:          self._pending_feature_error = None
500:          self._current_state = None
501:          self._callback_failed = False
502: +        self._prompt_context = None
503: +        self._block_prompt_context = None
504: +        self._recovery_retries = {}
505: +        self._cleanup_retries = {}
506: +        self._replay_context_target = None
507: +        self._context_reset_attempted = False
508: +        self._in_context_reset = False
509:  
510:      def _call_feature(self, callback, *args):
511:          """Run a feature callback and apply best-effort policy at this boundary."""
512:          try:
513:              return callback(*args)
514:          except Exception as error:
515: -            if not self._continue_on_error:
516: -                raise
517: -            self.logger.exception("Bootstrap feature callback failed")
518: -            self._pending_feature_error = error
519: -            self._callback_failed = True
520: +            self._handle_work_error(error, from_callback=True)
521:              return None
522:  
523: +    def _handle_work_error(self, error, *, from_callback=False):
524: +        """Apply the configured failure policy after feature/recovery decisions."""
525: +        if not self._continue_on_error:
526: +            raise error
527: +        if from_callback:
528: +            self.logger.exception("Bootstrap feature callback failed")
529: +        else:
530: +            self.logger.error("Bootstrap work failed: %s", error, exc_info=error)
531: +        self._pending_feature_error = error
532: +        self._callback_failed = True
533: +
534:      def _recover_feature_error(self, *, at_idle_prompt=False):
535:          error = self._pending_feature_error
536:          if error is None or (
537:              self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
538:          ):
539: @@ -143,10 +163,13 @@ class FOSCommander:
540:              self._inflight = None
541:              self._suppression.close()
542:              self._suppression = ExitStack()
543:  
544:          self._in_cleanup = False
545: +        self._replay_context_target = None
546: +        self._in_context_reset = False
547: +        self._cleanup_retries.clear()
548:          self._feature_errors.append((failed_name, str(error)))
549:          return failed_name
550:  
551:      def record_feature_error(self, name, error):
552:          """Record a recoverable bootstrap problem without stopping the queue."""
553: @@ -184,10 +207,14 @@ class FOSCommander:
554:          if self.busy:
555:              raise RuntimeError("Cannot replace an active command block")
556:          commands = tuple(flatten_commands(block))
557:          self._active_commands = commands
558:          self._pending = deque(commands)
559: +        self._block_prompt_context = self._prompt_context
560: +        self._recovery_retries = {}
561: +        self._replay_context_target = None
562: +        self._context_reset_attempted = False
563:  
564:      def feature_complete(self, feature):
565:          if feature is not self._active_feature:
566:              return
567:          if self.busy:
568: @@ -242,10 +269,18 @@ class FOSCommander:
569:  
570:      def on_state(self, state, output):
571:          """Called by the driver for every recognized serial state."""
572:          self._current_state = state
573:          self._callback_failed = False
574: +        if state == FOSCliState.CMD_PROMPT:
575: +            context = self._extract_prompt_context(output)
576: +            if context is not None:
577: +                self._prompt_context = context
578: +            # Some releases return directly to a usable prompt after login,
579: +            # without a Welcome banner. The prompt also ends session recovery.
580: +            self._authenticated_once = True
581: +            self._recovering = False
582:          if self._pending_feature_error is not None:
583:              if state == FOSCliState.CMD_PROMPT:
584:                  self._recover_feature_error()
585:              elif state == FOSCliState.SESSION_LOST:
586:                  self._session_epoch += 1
587: @@ -275,13 +310,10 @@ class FOSCommander:
588:              return
589:          if state == FOSCliState.CREDENTIAL_ACCEPTED:
590:              self._authenticated_once = True
591:              self._recovering = False
592:              return
593: -        if state == FOSCliState.CMD_PROMPT:
594: -            self._authenticated_once = True
595: -
596:          if self._inflight and state in (
597:              self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
598:          ):
599:              self._complete_inflight(state)
600:              return
601: @@ -345,28 +377,41 @@ class FOSCommander:
602:          self._call_feature(self._active_feature.begin_activation)
603:          if self._pending_feature_error is None:
604:              self._call_feature(self._active_feature.activate)
605:  
606:      def _dispatch_next(self):
607: -        if self._inflight or self._recovering:
608: +        if self._inflight or self._recovering or self._pending_feature_error is not None:
609: +            return
610: +        if not self._restore_replay_context():
611:              return
612:          if not self._cleanup and self._active_feature is None:
613:              self._activate_next_feature()
614:              if self._active_feature is None:
615:                  return
616:          if self._cleanup:
617:              spec = self._cleanup.popleft()
618:              self._in_cleanup = True
619: +            block_index = None
620:          elif not self._pending:
621:              self._call_feature(self._active_feature.on_block_complete)
622:              return
623:          else:
624:              spec = self._pending.popleft()
625:              self._in_cleanup = False
626: +            block_index = len(self._active_commands) - len(self._pending) - 1
627: +        self._dispatch_command(spec, block_index)
628: +
629: +    def _dispatch_command(self, spec, block_index=None):
630:          self._attempt_number += 1
631:          self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)
632: -        if self._active_feature:
633: +        self._inflight.prompt_context_before = self._prompt_context
634: +        self._inflight.block_index = block_index
635: +        self._inflight.retry_count = (
636: +            self._cleanup_retries.get(id(spec), 0)
637: +            if self._in_cleanup else self._recovery_retries.get(block_index, 0)
638: +        )
639: +        if self._active_feature and not self._in_context_reset:
640:              self._call_feature(self._active_feature.on_command_dispatched, self._inflight)
641:              if self._pending_feature_error is not None:
642:                  return
643:          if spec.suppress_output:
644:              self._suppression.enter_context(self.terminal.suppress_output())
645: @@ -380,12 +425,34 @@ class FOSCommander:
646:      def _complete_inflight(self, state):
647:          attempt = self._inflight
648:          self._inflight = None
649:          self._suppression.close()
650:          self._suppression = ExitStack()
651: -        self._validate_completion(attempt, state)
652: +        attempt.prompt_context_after = self._prompt_context
653: +        if self._in_context_reset:
654: +            self._in_context_reset = False
655: +            self._dispatch_next()
656: +            return
657: +        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
658: +            self._handle_context_loss(attempt)
659: +            if self._pending_feature_error is not None:
660: +                self._recover_feature_error()
661: +            else:
662: +                self._dispatch_next()
663: +            return
664: +        try:
665: +            self._validate_completion(attempt, state)
666: +        except RuntimeError as error:
667: +            if state != FOSCliState.CMD_PROMPT:
668: +                # An interactive prompt cannot safely advance to another feature.
669: +                raise
670: +            self._handle_work_error(error)
671: +            if self._pending_feature_error is not None:
672: +                self._recover_feature_error()
673: +            return
674:          if self._in_cleanup:
675: +            self._cleanup_retries.pop(id(attempt.spec), None)
676:              self._in_cleanup = False
677:              self._dispatch_next()
678:              return
679:          if self._is_standard_output_command(attempt.spec):
680:              self._complete_standard_output_command(attempt)
681: @@ -404,24 +471,105 @@ class FOSCommander:
682:          if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:
683:              self._dispatch_next()
684:  
685:      @staticmethod
686:      def _validate_completion(attempt, state):
687: -        if attempt.spec.fail_on_error and (
688: +        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (
689:              failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))
690:          ):
691:              raise RuntimeError(
692: -                "FortiOS command failed "
693: +                f"FortiOS command {attempt.spec.line!r} failed "
694:                  f"(return code {failure.group(1).decode()})"
695:              )
696:          expected = attempt.spec.expected_completion_state
697:          if expected is not None and state != expected:
698:              raise RuntimeError(
699:                  "CLI command completed at unexpected prompt: "
700:                  f"expected {expected.name}, received {state.name}"
701:              )
702:  
703: +    def _prompt_context_changed(self, attempt):
704: +        before = attempt.prompt_context_before
705: +        after = attempt.prompt_context_after
706: +        return (
707: +            before is not None
708: +            and after is not None
709: +            and before != after
710: +            and not self._command_may_change_context(attempt.spec)
711: +        )
712: +
713: +    def _handle_context_loss(self, attempt):
714: +        reason = (
715: +            "CLI context changed from "
716: +            f"{self._format_prompt_context(attempt.prompt_context_before)} to "
717: +            f"{self._format_prompt_context(attempt.prompt_context_after)}"
718: +        )
719: +        if self._in_cleanup:
720: +            self._handle_work_error(RuntimeError(
721: +                f"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay"
722: +            ))
723: +            return
724: +        action = self._call_feature(self._active_feature.on_context_loss, attempt)
725: +        if self._pending_feature_error is not None:
726: +            return
727: +        if action == ContextLossAction.RESTART_BLOCK:
728: +            self._restart_active_block(attempt, reason)
729: +        elif action == ContextLossAction.FAIL:
730: +            self._handle_work_error(RuntimeError(
731: +                f"{reason} during {attempt.spec.line!r}; feature declined replay"
732: +            ))
733: +        else:
734: +            self._handle_work_error(ValueError(f"Unsupported context-loss action: {action!r}"))
735: +
736: +    def _restore_replay_context(self):
737: +        """Unwind a surviving partial scope once before replaying its openers."""
738: +        target = self._replay_context_target
739: +        if target is None:
740: +            return True
741: +        if self._prompt_context == target:
742: +            self._replay_context_target = None
743: +            return True
744: +        if self._context_reset_attempted:
745: +            self._handle_work_error(RuntimeError(
746: +                "Unable to restore CLI context before replay: expected "
747: +                f"{self._format_prompt_context(target)}, received "
748: +                f"{self._format_prompt_context(self._prompt_context or ())}"
749: +            ))
750: +            if self._pending_feature_error is not None:
751: +                self._recover_feature_error()
752: +            return False
753: +        self._context_reset_attempted = True
754: +        self._in_context_reset = True
755: +        self._dispatch_command(CommandSpec("abort", suppress_output=True))
756: +        return False
757: +
758: +    @staticmethod
759: +    def _command_may_change_context(spec):
760: +        if spec.continuation:
761: +            return False
762: +        command = spec.line.strip().lower()
763: +        return (
764: +            command.startswith(("config ", "edit "))
765: +            or command in {"next", "end", "abort", "exit", "quit"}
766: +            or command == "set vdom-mode multi-vdom"
767: +        )
768: +
769: +    @staticmethod
770: +    def _extract_prompt_context(output):
771: +        data = bytes(output)
772: +        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))
773: +        if not matches:
774: +            return None
775: +        return tuple(
776: +            item.decode(errors="replace")
777: +            for item in re.findall(rb"\(([^)]*)\)", matches[-1].group("context"))
778: +        )
779: +
780: +    @staticmethod
781: +    def _format_prompt_context(context):
782: +        return " ".join(f"({item})" for item in context) or "<top-level>"
783: +
784:      def _is_standard_output_command(self, spec):
785:          context = self._standard_output_context
786:          return context is not None and (
787:              spec.line == self._CONSOLE_INSPECT_LINE
788:              or (context.phase == "set-standard" and not self._pending)
789: @@ -466,11 +614,24 @@ class FOSCommander:
790:              return
791:          attempt = self._inflight
792:          self._inflight = None
793:          self._suppression.close()
794:          self._suppression = ExitStack()
795: +        if self._in_context_reset:
796: +            # Login may itself restore the target scope. The pending replay
797: +            # stays bounded by the original command's recovery allowance.
798: +            self._in_context_reset = False
799: +            return
800:          if self._in_cleanup:
801: +            retries = self._cleanup_retries.get(id(attempt.spec), 0)
802: +            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
803: +                self._handle_work_error(RuntimeError(
804: +                    f"Session lost repeatedly during cleanup {attempt.spec.line!r}; "
805: +                    "retry limit reached"
806: +                ))
807: +                return
808: +            self._cleanup_retries[id(attempt.spec)] = retries + 1
809:              self._cleanup.appendleft(attempt.spec)
810:              self._in_cleanup = False
811:              return
812:          self._schedule_feature_cleanup(self._active_feature, "interruption")
813:          action = self._call_feature(
814: @@ -481,24 +642,39 @@ class FOSCommander:
815:              return
816:          self.logger.info(
817:              f"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}"
818:          )
819:          action_handlers = {
820: -            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),
821: +            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(
822: +                attempt, "session lost"
823: +            ),
824:              SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),
825:              SessionLossAction.CONTINUE: lambda: self._pending.clear(),
826: -            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),
827: +            SessionLossAction.FAIL: lambda: self._handle_work_error(
828: +                RuntimeError(f"Session lost during {attempt.spec.line!r}")
829: +            ),
830:              SessionLossAction.VALIDATE: lambda: self._pending.clear(),
831:          }
832:          action_handlers[action]()
833:  
834: -    def _restart_active_block(self):
835: +    def _restart_active_block(self, attempt, reason):
836: +        retries = self._recovery_retries.get(attempt.block_index, 0)
837: +        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
838: +            self._handle_work_error(RuntimeError(
839: +                f"{reason} repeatedly during {attempt.spec.line!r}; "
840: +                f"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})"
841: +            ))
842: +            return
843: +        self._recovery_retries[attempt.block_index] = retries + 1
844:          self._pending = deque(self._active_commands)
845: -
846: -    @staticmethod
847: -    def _raise_session_loss(attempt):
848: -        raise RuntimeError(f"Session lost during {attempt.spec.line!r}")
849: +        self._replay_context_target = self._block_prompt_context
850: +        self._context_reset_attempted = False
851: +        self.logger.warning(
852: +            "%s during %s/%r; replaying block (command recovery %d/%d)",
853: +            reason, self._active_feature.name, attempt.spec.line,
854: +            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,
855: +        )
856:  
857:      def enqueue_runtime_feature(self, feature):
858:          return self.enqueue_runtime_features([feature])
859:  
860:      def enqueue_runtime_features(self, features):
861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py
862: index 4c2d808..3c112e1 100755
863: --- a/fortinet/common/launch.py
864: +++ b/fortinet/common/launch.py
865: @@ -30,11 +30,11 @@ from .features import (
866:      InstallPkiCertificates,
867:      ApplyStartupConfig,
868:      ValidateProduct,
869:  )
870:  from .env import get_env
871: -from .fos_cli_driver import FOSCliDriver
872: +from .fos_cli_driver import FOSCliDriver, KernelPanicError
873:  from .fos_commander import FOSCommander
874:  from .host_forwarded_bridge import HostForwardedBridge
875:  from .net_mgmt_strategy import NetMgmtStrategy
876:  from .passthrough_redirect import PassthroughRedirect
877:  from .terminal import Terminal
878: @@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):
879:          """
880:          if self._bootstrap_error is not None:
881:              return False
882:          try:
883:              self.driver.process_state()
884: +        except KernelPanicError:
885: +            self.stop()
886: +            raise
887:          except Exception as error:
888:              if self._exit_on_bootstrap_error or self.commander.startup_complete:
889:                  self.stop()
890:                  raise
891:              failed_work = self.commander.continue_after_error(
892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py
893: index 368238c..d124474 100644
894: --- a/fortinet/common/terminal.py
895: +++ b/fortinet/common/terminal.py
896: @@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():
897:  
898:  
899:  class Data:
900:      """A byte view returned by Terminal.expect with authority to discard itself."""
901:  
902: -    def __init__(self, value, discard_callback=None):
903: +    def __init__(self, value, discard_callback=None, *, received_new_data=None):
904:          self.value = bytes(value)
905:          self._discard_callback = discard_callback
906:          self.discarded = False
907: +        self.received_new_data = (
908: +            bool(self.value) if received_new_data is None else received_new_data
909: +        )
910:  
911:      def __bytes__(self):
912:          return self.value
913:  
914:      def __bool__(self):
915: @@ -213,36 +216,46 @@ class Terminal:
916:      def expect(self, regex_list, timeout=None):
917:          """Read until a pattern matches, retaining unmatched data across calls.
918:  
919:          The match ending earliest in the buffered stream wins. Data through that
920:          match is returned and discarded; data after it remains buffered.
921: +        On timeout, the entire unmatched buffer is returned for inspection and
922: +        stays buffered unless the caller explicitly discards it.
923:          """
924:          self._ensure_reader()
925:          deadline = None if timeout is None else time.monotonic() + timeout
926: -        received = bytearray()
927: +        received_new_data = False
928:          result = self._match(regex_list)
929:  
930:          while result is None:
931:              remaining = None if deadline is None else deadline - time.monotonic()
932:              if remaining is not None and remaining <= 0:
933: -                return -1, None, Data(bytes(received), self._discard_prefix)
934: +                return -1, None, Data(
935: +                    self._buffer,
936: +                    self._discard_prefix,
937: +                    received_new_data=received_new_data,
938: +                )
939:  
940:              data = self._read_queue.get(remaining)
941:              if data:
942:                  self._buffer.extend(data)
943:                  self._enforce_buffer_limit()
944: -                received.extend(data)
945: +                received_new_data = True
946:                  if (
947:                      get_env(RAW_SERIAL_LOG_ENV, "").lower() in ("1", "true", "yes")
948:                      and self._output_suppression_depth == 0
949:                  ):
950: -                    self._logger.log(TRACE_LEVEL - 1, f"buffer: {self._buffer}")
951: +                    self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")
952:                  result = self._match(regex_list)
953:                  continue
954:  
955:              if deadline is not None and time.monotonic() >= deadline:
956: -                return -1, None, Data(bytes(received), self._discard_prefix)
957: +                return -1, None, Data(
958: +                    self._buffer,
959: +                    self._discard_prefix,
960: +                    received_new_data=received_new_data,
961: +                )
962:  
963:          index, match = result
964:          consumed = bytes(self._buffer[:match.end()])
965:          stable_match = re.search(regex_list[index], consumed)
966:          del self._buffer[:match.end()]
967: @@ -251,11 +264,14 @@ class Terminal:
968:      def _discard_prefix(self, data):
969:          """Discard bytes that a caller has consumed from the retained buffer."""
970:          if not data:
971:              return
972:          if not self._buffer.startswith(data):
973: -            self._logger.debug("Refusing to discard non-prefix terminal output")
974: +            message = "Refusing to discard non-prefix terminal output"
975: +            if self._logger.isEnabledFor(TRACE_LEVEL):
976: +                message += f": data={data!r}; buffer={self._buffer!r}"
977: +            self._logger.warning(message)
978:              return
979:          del self._buffer[:len(data)]
980:  
981:      def _enforce_buffer_limit(self):
982:          if len(self._buffer) <= self._buffer_limit:
983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md
984: index 1d95aea..37c576e 100644
985: --- a/fortinet/fortigate/README.md
986: +++ b/fortinet/fortigate/README.md
987: @@ -167,11 +167,15 @@ config system global
988:      set alias "lab-fgt"
989:  end
990:  ```
991:  
992:  The importer validates basic `config` / `edit` / `next` / `end` nesting and
993: -fails startup on malformed structure.
994: +fails startup on malformed structure or unterminated quoted strings. Single-
995: +and double-quoted values can span lines. Newlines, whitespace, blank lines,
996: +and scope keywords inside a quoted value are preserved. Each continued line
997: +is sent only after the CLI's continuation prompt; the closing line must return
998: +to a command prompt. An unexpected prompt follows the bootstrap error policy.
999:  
1000:  The bootstrap DNS servers selected from the container resolver or
1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config
1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS
1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup
1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md
1005: index 9e11b86..74a118d 100644
1006: --- a/fortinet/fortigate/docker/README.md
1007: +++ b/fortinet/fortigate/docker/README.md
1008: @@ -35,12 +35,15 @@ Important behavior:
1009:  - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of
1010:    writing to the serial connection directly. The writer preserves write order
1011:    and sends one queued chunk at a time, so commander/driver state handling is
1012:    not paced by each scrapli write call.
1013:  - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte
1014: -  view of what was just read or matched, and timeout `Data` can discard bytes
1015: -  from the terminal's retained buffer.
1016: +  view of the matched prefix or, on timeout, the entire unmatched buffer.
1017: +  Inspecting timeout `Data` leaves those bytes buffered so later input can
1018: +  complete a partial token. Calling `discard()` explicitly consumes the view.
1019: +  `received_new_data` distinguishes fresh input from another inspection of the
1020: +  same retained bytes, so idle waits still advance the driver's stall timer.
1021:  - When multiple regexes match buffered output, the match that ends earliest
1022:    wins. This avoids later, broader prompt patterns swallowing earlier prompts.
1023:  - Matched bytes are consumed from the buffer; bytes after the match stay queued
1024:    for the next state parse.
1025:  - Timeout bytes are not consumed automatically. A command, feature, or commander
1026: @@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.
1027:  The dispatcher sends one command at a time and waits for an appropriate state
1028:  before continuing. By default, a command completes at the next command prompt.
1029:  Some commands override completion states, for example confirmation prompts or
1030:  reboot messages.
1031:  
1032: +Scope-closing commands (`next` and `end`) always capture their output and check
1033: +for `Command fail. Return code <number>`, including builds that append a period
1034: +after the code. A closing failure stops the feature before completion callbacks
1035: +or further commands, even when `fail_on_error=False`. It follows the bootstrap
1036: +error policy: abort normally, or skip the failed feature when
1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for
1038: +individual `set` commands, which can deliberately tolerate unsupported fields.
1039: +
1040:  Session loss is explicit. Each command carries a `SessionLossAction`:
1041:  
1042:  - `RESTART_BLOCK`: replay the current block from the start
1043:  - `COMPLETE_BLOCK`: treat the block as complete
1044:  - `CONTINUE`: do not replay the disruptive command
1045:  - `VALIDATE`: reserve for commands that need post-loss validation
1046: -- `FAIL`: raise immediately
1047: +- `FAIL`: report failure through the configured bootstrap error policy
1048:  
1049:  This matters because commands such as license restore and password updates can
1050:  drop the active admin session. Replaying them blindly can corrupt state or loop.
1051:  
1052: +Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.
1053: +The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,
1054: +commands that allow session-loss replay also allow context-loss replay; commands
1055: +with another session-loss policy decline context-loss replay unless explicitly
1056: +configured otherwise. Context loss does not invoke session-loss callbacks, since
1057: +those may commit credential or licensing transitions.
1058: +
1059: +The commander allows one recovery per command position within a submitted block,
1060: +shared between context loss and session loss. Recovery replays the block's scope
1061: +openers and commands. If necessary, the commander sends one `abort` to restore
1062: +the block's initial prompt context before replay. A repeated loss at the same
1063: +command or failure to restore that context follows the bootstrap error policy.
1064: +The allowance resets when the feature submits a new block. Cleanup commands also
1065: +have one session-loss retry. Attempts expose `retry_count` and the prompt context
1066: +before and after execution so features can make their recovery decision.
1067: +
1068:  The dispatcher also manages cleanup actions and standard-output contexts.
1069:  Features can request console output mode `standard` for machine-readable output;
1070:  the dispatcher detects the current console mode, changes it only when needed,
1071:  and restores `more` after the feature completes.
1072:  
1073: @@ -219,22 +246,23 @@ begin_activation()
1074:  on_command_dispatched(attempt)
1075:  on_output(output)
1076:  on_command_executed(command, state)
1077:  on_block_complete()
1078:  on_session_loss(attempt)
1079: +on_context_loss(attempt)
1080:  mark_completed()
1081:  ```
1082:  
1083:  Static command features subclass `StaticFeature`; they submit a fixed list of
1084:  blocks and complete after the last block. Dynamic features subclass `Feature`
1085:  and submit follow-up blocks based on command output or timer ticks.
1086:  
1087:  Current bootstrap stages are:
1088:  
1089:  - `disk-format`: formats additional disks after the first FortiGate log disk
1090: -- `admin`: disables password policy, creates/updates the desired admin, and
1091: -  handles session loss during password changes
1092: +- `admin`: disables password policy, creates/updates the desired admin, then
1093: +  logs out and waits for console authentication before later stages run
1094:  - `image-info`: reads `get system status` once and stores the parsed
1095:    platform, major, minor, patch, and build on `vm.fos_version` for later
1096:    features
1097:  - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against
1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint
1099: @@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept
1100:  a blank default password first. The driver keeps separate bootstrap and desired
1101:  credentials so it can answer prompts with the password that is valid at that
1102:  moment.
1103:  
1104:  The desired credentials are activated after the admin edit commits. Password
1105: -command output is checked for FortiOS command failures. After a password
1106: -change, the driver first tries the desired credentials. If FortiOS rejects
1107: +command output is checked for FortiOS command failures. After closing the admin
1108: +configuration, the feature sends `exit` and waits for a successful login and CLI
1109: +prompt before completing. A logout during the commit also activates the new
1110: +credentials without replaying the password change. The driver first tries the
1111: +desired credentials. If FortiOS rejects
1112:  them, it retries immediately with the previously accepted credentials, without
1113:  replacing the desired credentials used for later logins.
1114:  
1115:  ### Prompt patterns change during bootstrap
1116:  
1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py
1118: new file mode 100644
1119: index 0000000..7dc469b
1120: --- /dev/null
1121: +++ b/fortinet/tests/test_common_admin_credentials.py
1122: @@ -0,0 +1,154 @@
1123: +"""Admin credential commits followed by logout and console authentication."""
1124: +
1125: +import sys
1126: +import unittest
1127: +from pathlib import Path
1128: +from types import SimpleNamespace
1129: +from unittest.mock import MagicMock, patch
1130: +
1131: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1132: +
1133: +from fortinet.common.common import Credentials
1134: +from fortinet.common.features.credentials import CredentialsFeature
1135: +from fortinet.common.fos_cli_driver import FOSCliDriver
1136: +from fortinet.common.fos_commander import FOSCommander
1137: +from fortinet.common.terminal import Terminal
1138: +from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection
1139: +
1140: +
1141: +LOGIN = b"fw login:\r\n"
1142: +READY = b"Welcome!\r\nfw #\r\n"
1143: +ADMIN_PROMPT = b"fw (admin) #\r\n"
1144: +
1145: +
1146: +class AdminCredentialsTests(unittest.TestCase):
1147: +    def make_stack(self, *, password="newpass", username="admin",
1148: +                   auto_logout=None, authenticate=True, reject=False,
1149: +                   exit_works=True):
1150: +        logger = MagicMock()
1151: +        policy_prompt = b"fw (password-policy) #\r\n"
1152: +        old_password_responses = [READY]
1153: +        if password:
1154: +            old_password_responses.append(ADMIN_PROMPT)
1155: +        old_password_responses.append(b"Login incorrect\r\n" + LOGIN)
1156: +        end_count = 0
1157: +
1158: +        def end_response():
1159: +            nonlocal end_count
1160: +            end_count += 1
1161: +            return LOGIN if auto_logout == "end" and end_count == 2 else b"fw #\r\n"
1162: +
1163: +        login_reply = None if not authenticate else (
1164: +            b"Login incorrect\r\n" + LOGIN if reject else READY
1165: +        )
1166: +        responses = {
1167: +            b"admin\r": b"Password:",
1168: +            b"oldpass\r": lambda: old_password_responses.pop(0),
1169: +            b"config system password-policy\r": policy_prompt,
1170: +            b"set status disable\r": policy_prompt,
1171: +            b"config system admin\r": ADMIN_PROMPT,
1172: +            f"edit {username}\r".encode(): ADMIN_PROMPT,
1173: +            b"set accprofile super_admin\r": ADMIN_PROMPT,
1174: +            b"next\r": LOGIN if auto_logout == "next" else ADMIN_PROMPT,
1175: +            b"end\r": end_response,
1176: +            b"exit\r": LOGIN if exit_works else b"fw #\r\n",
1177: +            b"probe\r": b"fw #\r\n",
1178: +            (password + "\r").encode(): login_reply,
1179: +        }
1180: +        if username != "admin":
1181: +            responses[(username + "\r").encode()] = b"Password:"
1182: +        if password:
1183: +            responses[f"set password {password}\r".encode()] = (
1184: +                b"Please enter current administrator password: "
1185: +            )
1186: +        else:
1187: +            responses[b"unset password\r"] = ADMIN_PROMPT
1188: +
1189: +        connection = SerialConnection(responses)
1190: +        terminal = Terminal(connection, logger)
1191: +        commander = FOSCommander(terminal, logger)
1192: +        credentials = Credentials("admin", "oldpass")
1193: +        driver = FOSCliDriver(
1194: +            terminal, commander, credentials, logger, "bootstrap",
1195: +            MagicMock(), MagicMock(), allow_credential_recovery=True,
1196: +        )
1197: +

(Output capped at 50 KB. Showing lines 1-1197. Use offset=1198 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d11ba0001Sq44JpugFke1EN",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d114bf001b7PRnRynOkPtjP",
  "callID": "call_b09f730cfd1d4b748fc4609d",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt"
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\n2: index ea16d0f..1af3f4d 100644\n3: --- a/fortinet/common/cli_commands.py\n4: +++ b/fortinet/common/cli_commands.py\n5: @@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n6:      CONTINUE = auto()\n7:      VALIDATE = auto()\n8:      FAIL = auto()\n9:  \n10:  \n11: +class ContextLossAction(Enum):\n12: +    RESTART_BLOCK = auto()\n13: +    FAIL = auto()\n14: +\n15: +\n16:  @dataclass(frozen=True, init=False)\n17:  class CommandSpec:\n18:      line: str\n19:      completion_states: tuple = ()\n20:      capture_output: bool = False\n21:      suppress_output: bool = False\n22:      session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n23:      expected_completion_state: object = None\n24:      fail_on_error: bool = False\n25: +    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n26: +    continuation: bool = False\n27:  \n28:      def __init__(self, line, completion_states=(), capture_output=False,\n29:                   suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n30: -                 expected_completion_state=None, fail_on_error=False):\n31: +                 expected_completion_state=None, fail_on_error=False,\n32: +                 context_loss=None, continuation=False):\n33:          object.__setattr__(self, \"line\", line)\n34:          object.__setattr__(self, \"completion_states\", completion_states)\n35:          object.__setattr__(self, \"capture_output\", capture_output)\n36:          object.__setattr__(self, \"suppress_output\", suppress_output)\n37:          object.__setattr__(self, \"session_loss\", session_loss)\n38:          object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n39:          object.__setattr__(self, \"fail_on_error\", fail_on_error)\n40: +        object.__setattr__(self, \"continuation\", continuation)\n41: +        if context_loss is None:\n42: +            # Commands that must not replay after logout must not replay after\n43: +            # an unexpected scope exit either. Features can override this policy.\n44: +            context_loss = (\n45: +                ContextLossAction.RESTART_BLOCK\n46: +                if session_loss == SessionLossAction.RESTART_BLOCK\n47: +                else ContextLossAction.FAIL\n48: +            )\n49: +        object.__setattr__(self, \"context_loss\", context_loss)\n50:          self.__post_init__()\n51:  \n52:      def __post_init__(self):\n53:          if \"\\r\" in self.line or \"\\n\" in self.line:\n54:              raise ValueError(\"CLI commands must contain exactly one line\")\n55:  \n56: +    @property\n57: +    def closes_scope(self):\n58: +        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n59: +\n60:  \n61:  @dataclass\n62:  class CommandAttempt:\n63:      spec: CommandSpec\n64:      number: int\n65:      session_epoch: int\n66:      output: bytearray = field(default_factory=bytearray)\n67: +    prompt_context_before: tuple | None = None\n68: +    prompt_context_after: tuple | None = None\n69: +    block_index: int | None = None\n70: +    retry_count: int = 0\n71:  \n72:      def on_output(self, output):\n73: -        if not self.spec.capture_output:\n74: +        if not (self.spec.capture_output or self.spec.closes_scope):\n75:              return False\n76:          data = bytes(output)\n77:          self.output.extend(data)\n78:          output.discard(data)\n79:          return True\n80: @@ -69,11 +95,11 @@ class Scope:\n81:      @property\n82:      def close_line(self):\n83:          raise NotImplementedError\n84:  \n85:      def flatten(self):\n86: -        commands = [CommandSpec(self.open_line)]\n87: +        commands = flatten_commands(self.open_line)\n88:          for child in self.children:\n89:              commands.extend(flatten_commands(child))\n90:          commands.append(CommandSpec(self.close_line))\n91:          return commands\n92:  \n93: @@ -107,49 +133,43 @@ class SetValue:\n94:          self.fail_on_error = fail_on_error\n95:          self.validate_prompt = validate_prompt\n96:  \n97:      def flatten(self):\n98:          lines = str(self.value).strip().splitlines() or [\"\"]\n99: -        if len(lines) == 1:\n100: -            return [CommandSpec(\n101: -                f'set {self.field} \"{lines[0]}\"',\n102: -                capture_output=True,\n103: -                expected_completion_state=(\n104: -                    FOSCliState.CMD_PROMPT if self.validate_prompt else None\n105: -                ),\n106: -                fail_on_error=self.fail_on_error,\n107: -            )]\n108: -\n109: -        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n110: -        commands = [CommandSpec(\n111: -            f'set {self.field} \"{lines[0]}',\n112: -            completion_states=both_prompts,\n113: -            capture_output=True,\n114: -            expected_completion_state=(\n115: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n116: -            ),\n117: -            fail_on_error=self.fail_on_error,\n118: -        )]\n119: -        commands.extend(CommandSpec(\n120: -            line,\n121: -            completion_states=both_prompts,\n122: -            capture_output=True,\n123: -            expected_completion_state=(\n124: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n125: -            ),\n126: -            fail_on_error=self.fail_on_error,\n127: -        ) for line in lines[1:-1])\n128: +        lines[0] = f'set {self.field} \"{lines[0]}'\n129: +        lines[-1] += '\"'\n130: +        return _flatten_quoted_lines(\n131: +            lines, fail_on_error=self.fail_on_error,\n132: +            validate_prompt=self.validate_prompt,\n133: +        )\n134: +\n135: +\n136: +def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n137: +    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n138: +    commands = []\n139: +    for index, line in enumerate(lines):\n140: +        last_line = index == len(lines) - 1\n141: +        expected = (\n142: +            FOSCliState.CMD_PROMPT if last_line\n143: +            else FOSCliState.MULTILINE_PROMPT\n144: +        )\n145: +        completion_states = ()\n146: +        if len(lines) > 1:\n147: +            completion_states = (\n148: +                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n149: +                if last_line else\n150: +                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n151: +            )\n152:          commands.append(CommandSpec(\n153: -            f'{lines[-1]}\"',\n154: -            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),\n155: +            line,\n156: +            completion_states=completion_states,\n157:              capture_output=True,\n158: -            expected_completion_state=(\n159: -                FOSCliState.CMD_PROMPT if self.validate_prompt else None\n160: -            ),\n161: -            fail_on_error=self.fail_on_error,\n162: +            expected_completion_state=expected if validate_prompt else None,\n163: +            fail_on_error=fail_on_error,\n164: +            continuation=index > 0,\n165:          ))\n166: -        return commands\n167: +    return commands\n168:  \n169:  \n170:  class CommandSequence:\n171:      \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n172:  \n173: @@ -165,10 +185,12 @@ class CommandSequence:\n174:  \n175:  \n176:  def flatten_commands(value):\n177:      \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n178:      if isinstance(value, str):\n179: +        if \"\\n\" in value:\n180: +            return _flatten_quoted_lines(value.split(\"\\n\"))\n181:          return [CommandSpec(value)]\n182:      if isinstance(value, CommandSpec):\n183:          return [value]\n184:      if isinstance(value, (Scope, CommandSequence, SetValue)):\n185:          return value.flatten()\n186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py\n187: index 4ffb817..b020deb 100644\n188: --- a/fortinet/common/common.py\n189: +++ b/fortinet/common/common.py\n190: @@ -21,10 +21,11 @@ class FOSCliState(IntEnum):\n191:      CURRENT_PASSWORD = auto()\n192:      CONFIRMATION = auto()\n193:      CHANGE_PASSWORD_CONFIRM = auto()\n194:      MORE_PROMPT = auto()\n195:      MULTILINE_PROMPT = auto()\n196: +    KERNEL_PANIC = auto()\n197:      UNKNOWN = auto()  # Non-patterns from here on.\n198:      TN_TIMEOUT = auto()\n199:  \n200:  \n201:  GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n203:  )\n204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n209: +    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n210: +    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n211: +)\n212:  \n213:  DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n214:  DEFAULT_USERNAME = \"admin\"\n215:  DEFAULT_PASSWORD = DEFAULT_USERNAME\n216:  \n217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\n218: index 83ebc9b..5dd906a 100644\n219: --- a/fortinet/common/features/base.py\n220: +++ b/fortinet/common/features/base.py\n221: @@ -53,10 +53,14 @@ class Feature:\n222:          self.commander.feature_complete(self)\n223:  \n224:      def on_session_loss(self, attempt):\n225:          return attempt.spec.session_loss\n226:  \n227: +    def on_context_loss(self, attempt):\n228: +        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n229: +        return attempt.spec.context_loss\n230: +\n231:      def reversal_blocks(self):\n232:          \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n233:          return []\n234:  \n235:      def undo(self):\n236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\n237: index b8bc7de..af39225 100644\n238: --- a/fortinet/common/features/credentials.py\n239: +++ b/fortinet/common/features/credentials.py\n240: @@ -1,14 +1,15 @@\n241:  \"\"\"Administrator bootstrap feature.\"\"\"\n242:  \n243: -from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n244: +from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n245: +from ..common import FOSCliState\n246:  \n247:  from .base import StaticFeature\n248:  \n249:  \n250:  class CredentialsFeature(StaticFeature):\n251: -    \"\"\"Configure the administrator and change credentials after password loss.\"\"\"\n252: +    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n253:  \n254:      def __init__(self, vm, commander):\n255:          self._activate_after_admin_commit = False\n256:          self._desired_credentials_activated = False\n257:          self._password_change_committed = False\n258: @@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):\n259:                  fail_on_error=True,\n260:              ))\n261:          super().__init__(vm, commander, \"admin\", [\n262:              ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n263:              ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n264: +            CommandSequence(\"admin-relogin\", [CommandSpec(\n265: +                \"exit\",\n266: +                session_loss=SessionLossAction.CONTINUE,\n267: +                capture_output=True,\n268: +                fail_on_error=True,\n269: +                # A successful logout takes the session-loss path. Returning\n270: +                # straight to a CLI prompt must not count as verification.\n271: +                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n272: +            )]),\n273:          ], on_complete=lambda: self._activate_desired_credentials())\n274:  \n275: +    def on_command_dispatched(self, attempt):\n276: +        if attempt.spec.line == \"exit\":\n277: +            self._activate_desired_credentials()\n278: +        super().on_command_dispatched(attempt)\n279: +\n280:      def on_session_loss(self, attempt):\n281: +        if attempt.spec.line == \"exit\":\n282: +            # The commander resumes this block only at the authenticated CLI\n283: +            # prompt. Clear the logout command so it cannot be replayed.\n284: +            return SessionLossAction.CONTINUE\n285:          if self._is_password_command(attempt.spec.line):\n286:              self._activate_desired_credentials()\n287:              self._activate_after_admin_commit = False\n288:              return SessionLossAction.CONTINUE\n289: +        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n290: +            # Some releases log out during the commit instead of returning\n291: +            # its CLI prompt. Authenticate with the committed password.\n292: +            self._activate_desired_credentials()\n293: +            self._activate_after_admin_commit = False\n294: +            self._password_change_committed = True\n295: +            return SessionLossAction.CONTINUE\n296:          if self._password_change_committed:\n297:              # FortiOS may log out as the admin edit closes. The password\n298:              # command and `next` have already committed the new credentials,\n299:              # so replaying this block would use the previous password again.\n300:              return SessionLossAction.CONTINUE\n301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\n302: index 96a90d3..a5f0de7 100644\n303: --- a/fortinet/common/features/pki.py\n304: +++ b/fortinet/common/features/pki.py\n305: @@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):\n306:      @staticmethod\n307:      def _config_item_block(scope, name, children):\n308:          # A configuration attempt is deliberately best-effort: the feature\n309:          # must be able to inspect the result and fall back to the TFTP import\n310:          # path when a firmware release does not expose this config tree.  If\n311: -        # these wrapper commands keep ``fail_on_error`` enabled, the commander\n312: -        # raises before ``on_command_executed`` can record the failed config\n313: -        # attempt and select the fallback.\n314: +        # opening commands keep ``fail_on_error`` enabled, the commander raises\n315: +        # before ``on_command_executed`` can select that fallback. A return-code\n316: +        # failure from `next` or `end` is always fatal to the feature: the\n317: +        # commander checks scope commits even when fail_on_error is disabled.\n318:          def config_command(line):\n319:              return CommandSpec(line, capture_output=True, fail_on_error=False)\n320:  \n321:          return CommandSequence(f\"{scope}-{name}\", [\n322:              config_command(f\"config {scope}\"),\n323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\n324: index e404fc8..cb99aa4 100644\n325: --- a/fortinet/common/features/startup_config.py\n326: +++ b/fortinet/common/features/startup_config.py\n327: @@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):\n328:              \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n329:          )\n330:      return filtered\n331:  \n332:  \n333: +def _startup_config_commands(config):\n334: +    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n335: +    pending = []\n336: +    quote = None\n337: +    start_line = None\n338: +    for number, raw_line in enumerate(config, start=1):\n339: +        # Text mode normalizes file line endings. Only remove the delimiter;\n340: +        # whitespace and comment/scope-looking lines inside quotes are data.\n341: +        line = raw_line.removesuffix(\"\\n\")\n342: +        if not pending:\n343: +            line = line.lstrip()\n344: +            if not line or line.startswith(\"#\"):\n345: +                continue\n346: +            start_line = number\n347: +\n348: +        escaped = False\n349: +        for character in line:\n350: +            if escaped:\n351: +                escaped = False\n352: +            elif character == \"\\\\\":\n353: +                escaped = True\n354: +            elif character == quote:\n355: +                quote = None\n356: +            elif quote is None and character in {\"'\", '\"'}:\n357: +                quote = character\n358: +\n359: +        if quote is not None or escaped:\n360: +            pending.append(line)\n361: +            continue\n362: +        pending.append(line.rstrip())\n363: +        yield \"\\n\".join(pending)\n364: +        pending.clear()\n365: +\n366: +    if pending:\n367: +        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n368: +        raise ValueError(\n369: +            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n370: +        )\n371: +\n372: +\n373:  def parse_startup_config(path):\n374:      roots = []\n375:      stack = []\n376:      with open(path) as config:\n377: -        for raw_line in config:\n378: -            line = raw_line.strip()\n379: -            if not line or line.startswith(\"#\"):\n380: -                continue\n381: +        for line in _startup_config_commands(config):\n382:              if line.startswith(\"config \"):\n383:                  node = ConfigBlock(line[7:])\n384:                  (stack[-1].children if stack else roots).append(node)\n385:                  stack.append(node)\n386:              elif line.startswith(\"edit \"):\n387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\n388: index fa34100..b527816 100644\n389: --- a/fortinet/common/fos_cli_driver.py\n390: +++ b/fortinet/common/fos_cli_driver.py\n391: @@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10\n392:  EXPECT_TIMEOUT_SECONDS = 1\n393:  UNKNOWN_STALL_SECONDS = 30\n394:  UNKNOWN_STALL_NEWLINE_LIMIT = 3\n395:  \n396:  \n397: +class KernelPanicError(RuntimeError):\n398: +    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n399: +\n400: +\n401:  class FOSCliDriver:\n402:      \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n403:  \n404:      def __init__(\n405:          self,\n406: @@ -65,10 +69,11 @@ class FOSCliDriver:\n407:              FOSCliState.CMD_PROMPT: self._command_prompt,\n408:              FOSCliState.CMD_PROMPT_ECHO: None,\n409:              FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n410:              FOSCliState.LIC_FAIL: self._license_failed,\n411:              FOSCliState.TN_TIMEOUT: self._timeout,\n412: +            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n413:              FOSCliState.UNKNOWN: self._unknown,\n414:          }\n415:  \n416:      @property\n417:      def state_patterns(self):\n418: @@ -145,11 +150,14 @@ class FOSCliDriver:\n419:  \n420:      def _next_state(self):\n421:          index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n422:          if match:\n423:              return FOSCliState(index), output, True\n424: -        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False\n425: +        # A timeout exposes retained bytes too. Only fresh input should reset\n426: +        # the unknown-output stall timer; an unchanged buffer is still idle.\n427: +        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n428: +        return state, output, False\n429:  \n430:      def _handle_state(self, state):\n431:          handler = self._state_handlers.get(state)\n432:          if handler:\n433:              try:\n434: @@ -254,10 +262,14 @@ class FOSCliDriver:\n435:  \n436:      def _unknown(self):\n437:          if self._last_known_state == FOSCliState.REBOOTING:\n438:              self._idle_spins += 1\n439:  \n440: +    @staticmethod\n441: +    def _kernel_panic():\n442: +        raise KernelPanicError(\"Kernel panic detected on serial console\")\n443: +\n444:      def _note_unknown_output(self):\n445:          self._unknown_started_at = time.monotonic()\n446:  \n447:      def _recover_unknown_stall(self):\n448:          if self._unknown_started_at is None:\n449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\n450: index 26312cf..86b1be6 100644\n451: --- a/fortinet/common/fos_commander.py\n452: +++ b/fortinet/common/fos_commander.py\n453: @@ -10,24 +10,29 @@ from .cli_commands import (\n454:      CleanupAction,\n455:      CommandAttempt,\n456:      CommandSequence,\n457:      CommandSpec,\n458:      ConfigBlock,\n459: +    ContextLossAction,\n460:      SessionLossAction,\n461:      flatten_commands,\n462:  )\n463:  from .terminal import Data\n464: -from .common import FOSCliState, TRACE_LEVEL\n465: +from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n466:  \n467:  DISPATCHABLE_COMPLETION_STATES = {\n468:      FOSCliState.CMD_PROMPT,\n469:      FOSCliState.CONFIRMATION,\n470:      FOSCliState.MULTILINE_PROMPT,\n471:  }\n472:  COMMAND_FAILURE_PATTERN = re.compile(\n473:      rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n474:  )\n475: +CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n476: +    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n477: +    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n478: +)\n479:  \n480:  \n481:  @dataclass\n482:  class _StandardOutputContext:\n483:      feature: object\n484: @@ -35,10 +40,11 @@ class _StandardOutputContext:\n485:      phase: str = \"inspect\"\n486:      restore: bool = False\n487:  \n488:  \n489:  class FOSCommander:\n490: +    MAX_COMMAND_RECOVERY_RETRIES = 1\n491:      _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n492:      _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n493:      _CONSOLE_STANDARD_LINE = \"set output standard\"\n494:  \n495:      def __init__(self, terminal, logger, continue_on_error=False):\n496: @@ -65,23 +71,37 @@ class FOSCommander:\n497:          self._start_time = datetime.datetime.now()\n498:          self._continue_on_error = continue_on_error\n499:          self._pending_feature_error = None\n500:          self._current_state = None\n501:          self._callback_failed = False\n502: +        self._prompt_context = None\n503: +        self._block_prompt_context = None\n504: +        self._recovery_retries = {}\n505: +        self._cleanup_retries = {}\n506: +        self._replay_context_target = None\n507: +        self._context_reset_attempted = False\n508: +        self._in_context_reset = False\n509:  \n510:      def _call_feature(self, callback, *args):\n511:          \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n512:          try:\n513:              return callback(*args)\n514:          except Exception as error:\n515: -            if not self._continue_on_error:\n516: -                raise\n517: -            self.logger.exception(\"Bootstrap feature callback failed\")\n518: -            self._pending_feature_error = error\n519: -            self._callback_failed = True\n520: +            self._handle_work_error(error, from_callback=True)\n521:              return None\n522:  \n523: +    def _handle_work_error(self, error, *, from_callback=False):\n524: +        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n525: +        if not self._continue_on_error:\n526: +            raise error\n527: +        if from_callback:\n528: +            self.logger.exception(\"Bootstrap feature callback failed\")\n529: +        else:\n530: +            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n531: +        self._pending_feature_error = error\n532: +        self._callback_failed = True\n533: +\n534:      def _recover_feature_error(self, *, at_idle_prompt=False):\n535:          error = self._pending_feature_error\n536:          if error is None or (\n537:              self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n538:          ):\n539: @@ -143,10 +163,13 @@ class FOSCommander:\n540:              self._inflight = None\n541:              self._suppression.close()\n542:              self._suppression = ExitStack()\n543:  \n544:          self._in_cleanup = False\n545: +        self._replay_context_target = None\n546: +        self._in_context_reset = False\n547: +        self._cleanup_retries.clear()\n548:          self._feature_errors.append((failed_name, str(error)))\n549:          return failed_name\n550:  \n551:      def record_feature_error(self, name, error):\n552:          \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n553: @@ -184,10 +207,14 @@ class FOSCommander:\n554:          if self.busy:\n555:              raise RuntimeError(\"Cannot replace an active command block\")\n556:          commands = tuple(flatten_commands(block))\n557:          self._active_commands = commands\n558:          self._pending = deque(commands)\n559: +        self._block_prompt_context = self._prompt_context\n560: +        self._recovery_retries = {}\n561: +        self._replay_context_target = None\n562: +        self._context_reset_attempted = False\n563:  \n564:      def feature_complete(self, feature):\n565:          if feature is not self._active_feature:\n566:              return\n567:          if self.busy:\n568: @@ -242,10 +269,18 @@ class FOSCommander:\n569:  \n570:      def on_state(self, state, output):\n571:          \"\"\"Called by the driver for every recognized serial state.\"\"\"\n572:          self._current_state = state\n573:          self._callback_failed = False\n574: +        if state == FOSCliState.CMD_PROMPT:\n575: +            context = self._extract_prompt_context(output)\n576: +            if context is not None:\n577: +                self._prompt_context = context\n578: +            # Some releases return directly to a usable prompt after login,\n579: +            # without a Welcome banner. The prompt also ends session recovery.\n580: +            self._authenticated_once = True\n581: +            self._recovering = False\n582:          if self._pending_feature_error is not None:\n583:              if state == FOSCliState.CMD_PROMPT:\n584:                  self._recover_feature_error()\n585:              elif state == FOSCliState.SESSION_LOST:\n586:                  self._session_epoch += 1\n587: @@ -275,13 +310,10 @@ class FOSCommander:\n588:              return\n589:          if state == FOSCliState.CREDENTIAL_ACCEPTED:\n590:              self._authenticated_once = True\n591:              self._recovering = False\n592:              return\n593: -        if state == FOSCliState.CMD_PROMPT:\n594: -            self._authenticated_once = True\n595: -\n596:          if self._inflight and state in (\n597:              self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n598:          ):\n599:              self._complete_inflight(state)\n600:              return\n601: @@ -345,28 +377,41 @@ class FOSCommander:\n602:          self._call_feature(self._active_feature.begin_activation)\n603:          if self._pending_feature_error is None:\n604:              self._call_feature(self._active_feature.activate)\n605:  \n606:      def _dispatch_next(self):\n607: -        if self._inflight or self._recovering:\n608: +        if self._inflight or self._recovering or self._pending_feature_error is not None:\n609: +            return\n610: +        if not self._restore_replay_context():\n611:              return\n612:          if not self._cleanup and self._active_feature is None:\n613:              self._activate_next_feature()\n614:              if self._active_feature is None:\n615:                  return\n616:          if self._cleanup:\n617:              spec = self._cleanup.popleft()\n618:              self._in_cleanup = True\n619: +            block_index = None\n620:          elif not self._pending:\n621:              self._call_feature(self._active_feature.on_block_complete)\n622:              return\n623:          else:\n624:              spec = self._pending.popleft()\n625:              self._in_cleanup = False\n626: +            block_index = len(self._active_commands) - len(self._pending) - 1\n627: +        self._dispatch_command(spec, block_index)\n628: +\n629: +    def _dispatch_command(self, spec, block_index=None):\n630:          self._attempt_number += 1\n631:          self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n632: -        if self._active_feature:\n633: +        self._inflight.prompt_context_before = self._prompt_context\n634: +        self._inflight.block_index = block_index\n635: +        self._inflight.retry_count = (\n636: +            self._cleanup_retries.get(id(spec), 0)\n637: +            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n638: +        )\n639: +        if self._active_feature and not self._in_context_reset:\n640:              self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n641:              if self._pending_feature_error is not None:\n642:                  return\n643:          if spec.suppress_output:\n644:              self._suppression.enter_context(self.terminal.suppress_output())\n645: @@ -380,12 +425,34 @@ class FOSCommander:\n646:      def _complete_inflight(self, state):\n647:          attempt = self._inflight\n648:          self._inflight = None\n649:          self._suppression.close()\n650:          self._suppression = ExitStack()\n651: -        self._validate_completion(attempt, state)\n652: +        attempt.prompt_context_after = self._prompt_context\n653: +        if self._in_context_reset:\n654: +            self._in_context_reset = False\n655: +            self._dispatch_next()\n656: +            return\n657: +        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n658: +            self._handle_context_loss(attempt)\n659: +            if self._pending_feature_error is not None:\n660: +                self._recover_feature_error()\n661: +            else:\n662: +                self._dispatch_next()\n663: +            return\n664: +        try:\n665: +            self._validate_completion(attempt, state)\n666: +        except RuntimeError as error:\n667: +            if state != FOSCliState.CMD_PROMPT:\n668: +                # An interactive prompt cannot safely advance to another feature.\n669: +                raise\n670: +            self._handle_work_error(error)\n671: +            if self._pending_feature_error is not None:\n672: +                self._recover_feature_error()\n673: +            return\n674:          if self._in_cleanup:\n675: +            self._cleanup_retries.pop(id(attempt.spec), None)\n676:              self._in_cleanup = False\n677:              self._dispatch_next()\n678:              return\n679:          if self._is_standard_output_command(attempt.spec):\n680:              self._complete_standard_output_command(attempt)\n681: @@ -404,24 +471,105 @@ class FOSCommander:\n682:          if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n683:              self._dispatch_next()\n684:  \n685:      @staticmethod\n686:      def _validate_completion(attempt, state):\n687: -        if attempt.spec.fail_on_error and (\n688: +        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n689:              failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n690:          ):\n691:              raise RuntimeError(\n692: -                \"FortiOS command failed \"\n693: +                f\"FortiOS command {attempt.spec.line!r} failed \"\n694:                  f\"(return code {failure.group(1).decode()})\"\n695:              )\n696:          expected = attempt.spec.expected_completion_state\n697:          if expected is not None and state != expected:\n698:              raise RuntimeError(\n699:                  \"CLI command completed at unexpected prompt: \"\n700:                  f\"expected {expected.name}, received {state.name}\"\n701:              )\n702:  \n703: +    def _prompt_context_changed(self, attempt):\n704: +        before = attempt.prompt_context_before\n705: +        after = attempt.prompt_context_after\n706: +        return (\n707: +            before is not None\n708: +            and after is not None\n709: +            and before != after\n710: +            and not self._command_may_change_context(attempt.spec)\n711: +        )\n712: +\n713: +    def _handle_context_loss(self, attempt):\n714: +        reason = (\n715: +            \"CLI context changed from \"\n716: +            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n717: +            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n718: +        )\n719: +        if self._in_cleanup:\n720: +            self._handle_work_error(RuntimeError(\n721: +                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n722: +            ))\n723: +            return\n724: +        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n725: +        if self._pending_feature_error is not None:\n726: +            return\n727: +        if action == ContextLossAction.RESTART_BLOCK:\n728: +            self._restart_active_block(attempt, reason)\n729: +        elif action == ContextLossAction.FAIL:\n730: +            self._handle_work_error(RuntimeError(\n731: +                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n732: +            ))\n733: +        else:\n734: +            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n735: +\n736: +    def _restore_replay_context(self):\n737: +        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n738: +        target = self._replay_context_target\n739: +        if target is None:\n740: +            return True\n741: +        if self._prompt_context == target:\n742: +            self._replay_context_target = None\n743: +            return True\n744: +        if self._context_reset_attempted:\n745: +            self._handle_work_error(RuntimeError(\n746: +                \"Unable to restore CLI context before replay: expected \"\n747: +                f\"{self._format_prompt_context(target)}, received \"\n748: +                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n749: +            ))\n750: +            if self._pending_feature_error is not None:\n751: +                self._recover_feature_error()\n752: +            return False\n753: +        self._context_reset_attempted = True\n754: +        self._in_context_reset = True\n755: +        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n756: +        return False\n757: +\n758: +    @staticmethod\n759: +    def _command_may_change_context(spec):\n760: +        if spec.continuation:\n761: +            return False\n762: +        command = spec.line.strip().lower()\n763: +        return (\n764: +            command.startswith((\"config \", \"edit \"))\n765: +            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n766: +            or command == \"set vdom-mode multi-vdom\"\n767: +        )\n768: +\n769: +    @staticmethod\n770: +    def _extract_prompt_context(output):\n771: +        data = bytes(output)\n772: +        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n773: +        if not matches:\n774: +            return None\n775: +        return tuple(\n776: +            item.decode(errors=\"replace\")\n777: +            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n778: +        )\n779: +\n780: +    @staticmethod\n781: +    def _format_prompt_context(context):\n782: +        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n783: +\n784:      def _is_standard_output_command(self, spec):\n785:          context = self._standard_output_context\n786:          return context is not None and (\n787:              spec.line == self._CONSOLE_INSPECT_LINE\n788:              or (context.phase == \"set-standard\" and not self._pending)\n789: @@ -466,11 +614,24 @@ class FOSCommander:\n790:              return\n791:          attempt = self._inflight\n792:          self._inflight = None\n793:          self._suppression.close()\n794:          self._suppression = ExitStack()\n795: +        if self._in_context_reset:\n796: +            # Login may itself restore the target scope. The pending replay\n797: +            # stays bounded by the original command's recovery allowance.\n798: +            self._in_context_reset = False\n799: +            return\n800:          if self._in_cleanup:\n801: +            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n802: +            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n803: +                self._handle_work_error(RuntimeError(\n804: +                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n805: +                    \"retry limit reached\"\n806: +                ))\n807: +                return\n808: +            self._cleanup_retries[id(attempt.spec)] = retries + 1\n809:              self._cleanup.appendleft(attempt.spec)\n810:              self._in_cleanup = False\n811:              return\n812:          self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n813:          action = self._call_feature(\n814: @@ -481,24 +642,39 @@ class FOSCommander:\n815:              return\n816:          self.logger.info(\n817:              f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n818:          )\n819:          action_handlers = {\n820: -            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),\n821: +            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n822: +                attempt, \"session lost\"\n823: +            ),\n824:              SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n825:              SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n826: -            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),\n827: +            SessionLossAction.FAIL: lambda: self._handle_work_error(\n828: +                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n829: +            ),\n830:              SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n831:          }\n832:          action_handlers[action]()\n833:  \n834: -    def _restart_active_block(self):\n835: +    def _restart_active_block(self, attempt, reason):\n836: +        retries = self._recovery_retries.get(attempt.block_index, 0)\n837: +        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n838: +            self._handle_work_error(RuntimeError(\n839: +                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n840: +                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n841: +            ))\n842: +            return\n843: +        self._recovery_retries[attempt.block_index] = retries + 1\n844:          self._pending = deque(self._active_commands)\n845: -\n846: -    @staticmethod\n847: -    def _raise_session_loss(attempt):\n848: -        raise RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n849: +        self._replay_context_target = self._block_prompt_context\n850: +        self._context_reset_attempted = False\n851: +        self.logger.warning(\n852: +            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n853: +            reason, self._active_feature.name, attempt.spec.line,\n854: +            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n855: +        )\n856:  \n857:      def enqueue_runtime_feature(self, feature):\n858:          return self.enqueue_runtime_features([feature])\n859:  \n860:      def enqueue_runtime_features(self, features):\n861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\n862: index 4c2d808..3c112e1 100755\n863: --- a/fortinet/common/launch.py\n864: +++ b/fortinet/common/launch.py\n865: @@ -30,11 +30,11 @@ from .features import (\n866:      InstallPkiCertificates,\n867:      ApplyStartupConfig,\n868:      ValidateProduct,\n869:  )\n870:  from .env import get_env\n871: -from .fos_cli_driver import FOSCliDriver\n872: +from .fos_cli_driver import FOSCliDriver, KernelPanicError\n873:  from .fos_commander import FOSCommander\n874:  from .host_forwarded_bridge import HostForwardedBridge\n875:  from .net_mgmt_strategy import NetMgmtStrategy\n876:  from .passthrough_redirect import PassthroughRedirect\n877:  from .terminal import Terminal\n878: @@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):\n879:          \"\"\"\n880:          if self._bootstrap_error is not None:\n881:              return False\n882:          try:\n883:              self.driver.process_state()\n884: +        except KernelPanicError:\n885: +            self.stop()\n886: +            raise\n887:          except Exception as error:\n888:              if self._exit_on_bootstrap_error or self.commander.startup_complete:\n889:                  self.stop()\n890:                  raise\n891:              failed_work = self.commander.continue_after_error(\n892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\n893: index 368238c..d124474 100644\n894: --- a/fortinet/common/terminal.py\n895: +++ b/fortinet/common/terminal.py\n896: @@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():\n897:  \n898:  \n899:  class Data:\n900:      \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n901:  \n902: -    def __init__(self, value, discard_callback=None):\n903: +    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n904:          self.value = bytes(value)\n905:          self._discard_callback = discard_callback\n906:          self.discarded = False\n907: +        self.received_new_data = (\n908: +            bool(self.value) if received_new_data is None else received_new_data\n909: +        )\n910:  \n911:      def __bytes__(self):\n912:          return self.value\n913:  \n914:      def __bool__(self):\n915: @@ -213,36 +216,46 @@ class Terminal:\n916:      def expect(self, regex_list, timeout=None):\n917:          \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n918:  \n919:          The match ending earliest in the buffered stream wins. Data through that\n920:          match is returned and discarded; data after it remains buffered.\n921: +        On timeout, the entire unmatched buffer is returned for inspection and\n922: +        stays buffered unless the caller explicitly discards it.\n923:          \"\"\"\n924:          self._ensure_reader()\n925:          deadline = None if timeout is None else time.monotonic() + timeout\n926: -        received = bytearray()\n927: +        received_new_data = False\n928:          result = self._match(regex_list)\n929:  \n930:          while result is None:\n931:              remaining = None if deadline is None else deadline - time.monotonic()\n932:              if remaining is not None and remaining <= 0:\n933: -                return -1, None, Data(bytes(received), self._discard_prefix)\n934: +                return -1, None, Data(\n935: +                    self._buffer,\n936: +                    self._discard_prefix,\n937: +                    received_new_data=received_new_data,\n938: +                )\n939:  \n940:              data = self._read_queue.get(remaining)\n941:              if data:\n942:                  self._buffer.extend(data)\n943:                  self._enforce_buffer_limit()\n944: -                received.extend(data)\n945: +                received_new_data = True\n946:                  if (\n947:                      get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n948:                      and self._output_suppression_depth == 0\n949:                  ):\n950: -                    self._logger.log(TRACE_LEVEL - 1, f\"buffer: {self._buffer}\")\n951: +                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n952:                  result = self._match(regex_list)\n953:                  continue\n954:  \n955:              if deadline is not None and time.monotonic() >= deadline:\n956: -                return -1, None, Data(bytes(received), self._discard_prefix)\n957: +                return -1, None, Data(\n958: +                    self._buffer,\n959: +                    self._discard_prefix,\n960: +                    received_new_data=received_new_data,\n961: +                )\n962:  \n963:          index, match = result\n964:          consumed = bytes(self._buffer[:match.end()])\n965:          stable_match = re.search(regex_list[index], consumed)\n966:          del self._buffer[:match.end()]\n967: @@ -251,11 +264,14 @@ class Terminal:\n968:      def _discard_prefix(self, data):\n969:          \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n970:          if not data:\n971:              return\n972:          if not self._buffer.startswith(data):\n973: -            self._logger.debug(\"Refusing to discard non-prefix terminal output\")\n974: +            message = \"Refusing to discard non-prefix terminal output\"\n975: +            if self._logger.isEnabledFor(TRACE_LEVEL):\n976: +                message += f\": data={data!r}; buffer={self._buffer!r}\"\n977: +            self._logger.warning(message)\n978:              return\n979:          del self._buffer[:len(data)]\n980:  \n981:      def _enforce_buffer_limit(self):\n982:          if len(self._buffer) <= self._buffer_limit:\n983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\n984: index 1d95aea..37c576e 100644\n985: --- a/fortinet/fortigate/README.md\n986: +++ b/fortinet/fortigate/README.md\n987: @@ -167,11 +167,15 @@ config system global\n988:      set alias \"lab-fgt\"\n989:  end\n990:  ```\n991:  \n992:  The importer validates basic `config` / `edit` / `next` / `end` nesting and\n993: -fails startup on malformed structure.\n994: +fails startup on malformed structure or unterminated quoted strings. Single-\n995: +and double-quoted values can span lines. Newlines, whitespace, blank lines,\n996: +and scope keywords inside a quoted value are preserved. Each continued line\n997: +is sent only after the CLI's continuation prompt; the closing line must return\n998: +to a command prompt. An unexpected prompt follows the bootstrap error policy.\n999:  \n1000:  The bootstrap DNS servers selected from the container resolver or\n1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\n1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\n1005: index 9e11b86..74a118d 100644\n1006: --- a/fortinet/fortigate/docker/README.md\n1007: +++ b/fortinet/fortigate/docker/README.md\n1008: @@ -35,12 +35,15 @@ Important behavior:\n1009:  - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n1010:    writing to the serial connection directly. The writer preserves write order\n1011:    and sends one queued chunk at a time, so commander/driver state handling is\n1012:    not paced by each scrapli write call.\n1013:  - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n1014: -  view of what was just read or matched, and timeout `Data` can discard bytes\n1015: -  from the terminal's retained buffer.\n1016: +  view of the matched prefix or, on timeout, the entire unmatched buffer.\n1017: +  Inspecting timeout `Data` leaves those bytes buffered so later input can\n1018: +  complete a partial token. Calling `discard()` explicitly consumes the view.\n1019: +  `received_new_data` distinguishes fresh input from another inspection of the\n1020: +  same retained bytes, so idle waits still advance the driver's stall timer.\n1021:  - When multiple regexes match buffered output, the match that ends earliest\n1022:    wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n1023:  - Matched bytes are consumed from the buffer; bytes after the match stay queued\n1024:    for the next state parse.\n1025:  - Timeout bytes are not consumed automatically. A command, feature, or commander\n1026: @@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.\n1027:  The dispatcher sends one command at a time and waits for an appropriate state\n1028:  before continuing. By default, a command completes at the next command prompt.\n1029:  Some commands override completion states, for example confirmation prompts or\n1030:  reboot messages.\n1031:  \n1032: +Scope-closing commands (`next` and `end`) always capture their output and check\n1033: +for `Command fail. Return code <number>`, including builds that append a period\n1034: +after the code. A closing failure stops the feature before completion callbacks\n1035: +or further commands, even when `fail_on_error=False`. It follows the bootstrap\n1036: +error policy: abort normally, or skip the failed feature when\n1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n1038: +individual `set` commands, which can deliberately tolerate unsupported fields.\n1039: +\n1040:  Session loss is explicit. Each command carries a `SessionLossAction`:\n1041:  \n1042:  - `RESTART_BLOCK`: replay the current block from the start\n1043:  - `COMPLETE_BLOCK`: treat the block as complete\n1044:  - `CONTINUE`: do not replay the disruptive command\n1045:  - `VALIDATE`: reserve for commands that need post-loss validation\n1046: -- `FAIL`: raise immediately\n1047: +- `FAIL`: report failure through the configured bootstrap error policy\n1048:  \n1049:  This matters because commands such as license restore and password updates can\n1050:  drop the active admin session. Replaying them blindly can corrupt state or loop.\n1051:  \n1052: +Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n1053: +The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n1054: +commands that allow session-loss replay also allow context-loss replay; commands\n1055: +with another session-loss policy decline context-loss replay unless explicitly\n1056: +configured otherwise. Context loss does not invoke session-loss callbacks, since\n1057: +those may commit credential or licensing transitions.\n1058: +\n1059: +The commander allows one recovery per command position within a submitted block,\n1060: +shared between context loss and session loss. Recovery replays the block's scope\n1061: +openers and commands. If necessary, the commander sends one `abort` to restore\n1062: +the block's initial prompt context before replay. A repeated loss at the same\n1063: +command or failure to restore that context follows the bootstrap error policy.\n1064: +The allowance resets when the feature submits a new block. Cleanup commands also\n1065: +have one session-loss retry. Attempts expose `retry_count` and the prompt context\n1066: +before and after execution so features can make their recovery decision.\n1067: +\n1068:  The dispatcher also manages cleanup actions and standard-output contexts.\n1069:  Features can request console output mode `standard` for machine-readable output;\n1070:  the dispatcher detects the current console mode, changes it only when needed,\n1071:  and restores `more` after the feature completes.\n1072:  \n1073: @@ -219,22 +246,23 @@ begin_activation()\n1074:  on_command_dispatched(attempt)\n1075:  on_output(output)\n1076:  on_command_executed(command, state)\n1077:  on_block_complete()\n1078:  on_session_loss(attempt)\n1079: +on_context_loss(attempt)\n1080:  mark_completed()\n1081:  ```\n1082:  \n1083:  Static command features subclass `StaticFeature`; they submit a fixed list of\n1084:  blocks and complete after the last block. Dynamic features subclass `Feature`\n1085:  and submit follow-up blocks based on command output or timer ticks.\n1086:  \n1087:  Current bootstrap stages are:\n1088:  \n1089:  - `disk-format`: formats additional disks after the first FortiGate log disk\n1090: -- `admin`: disables password policy, creates/updates the desired admin, and\n1091: -  handles session loss during password changes\n1092: +- `admin`: disables password policy, creates/updates the desired admin, then\n1093: +  logs out and waits for console authentication before later stages run\n1094:  - `image-info`: reads `get system status` once and stores the parsed\n1095:    platform, major, minor, patch, and build on `vm.fos_version` for later\n1096:    features\n1097:  - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n1099: @@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept\n1100:  a blank default password first. The driver keeps separate bootstrap and desired\n1101:  credentials so it can answer prompts with the password that is valid at that\n1102:  moment.\n1103:  \n1104:  The desired credentials are activated after the admin edit commits. Password\n1105: -command output is checked for FortiOS command failures. After a password\n1106: -change, the driver first tries the desired credentials. If FortiOS rejects\n1107: +command output is checked for FortiOS command failures. After closing the admin\n1108: +configuration, the feature sends `exit` and waits for a successful login and CLI\n1109: +prompt before completing. A logout during the commit also activates the new\n1110: +credentials without replaying the password change. The driver first tries the\n1111: +desired credentials. If FortiOS rejects\n1112:  them, it retries immediately with the previously accepted credentials, without\n1113:  replacing the desired credentials used for later logins.\n1114:  \n1115:  ### Prompt patterns change during bootstrap\n1116:  \n1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\n1118: new file mode 100644\n1119: index 0000000..7dc469b\n1120: --- /dev/null\n1121: +++ b/fortinet/tests/test_common_admin_credentials.py\n1122: @@ -0,0 +1,154 @@\n1123: +\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n1124: +\n1125: +import sys\n1126: +import unittest\n1127: +from pathlib import Path\n1128: +from types import SimpleNamespace\n1129: +from unittest.mock import MagicMock, patch\n1130: +\n1131: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1132: +\n1133: +from fortinet.common.common import Credentials\n1134: +from fortinet.common.features.credentials import CredentialsFeature\n1135: +from fortinet.common.fos_cli_driver import FOSCliDriver\n1136: +from fortinet.common.fos_commander import FOSCommander\n1137: +from fortinet.common.terminal import Terminal\n1138: +from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n1139: +\n1140: +\n1141: +LOGIN = b\"fw login:\\r\\n\"\n1142: +READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n1143: +ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n1144: +\n1145: +\n1146: +class AdminCredentialsTests(unittest.TestCase):\n1147: +    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n1148: +                   auto_logout=None, authenticate=True, reject=False,\n1149: +                   exit_works=True):\n1150: +        logger = MagicMock()\n1151: +        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n1152: +        old_password_responses = [READY]\n1153: +        if password:\n1154: +            old_password_responses.append(ADMIN_PROMPT)\n1155: +        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n1156: +        end_count = 0\n1157: +\n1158: +        def end_response():\n1159: +            nonlocal end_count\n1160: +            end_count += 1\n1161: +            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n1162: +\n1163: +        login_reply = None if not authenticate else (\n1164: +            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n1165: +        )\n1166: +        responses = {\n1167: +            b\"admin\\r\": b\"Password:\",\n1168: +            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n1169: +            b\"config system password-policy\\r\": policy_prompt,\n1170: +            b\"set status disable\\r\": policy_prompt,\n1171: +            b\"config system admin\\r\": ADMIN_PROMPT,\n1172: +            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n1173: +            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n1174: +            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n1175: +            b\"end\\r\": end_response,\n1176: +            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n1177: +            b\"probe\\r\": b\"fw #\\r\\n\",\n1178: +            (password + \"\\r\").encode(): login_reply,\n1179: +        }\n1180: +        if username != \"admin\":\n1181: +            responses[(username + \"\\r\").encode()] = b\"Password:\"\n1182: +        if password:\n1183: +            responses[f\"set password {password}\\r\".encode()] = (\n1184: +                b\"Please enter current administrator password: \"\n1185: +            )\n1186: +        else:\n1187: +            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n1188: +\n1189: +        connection = SerialConnection(responses)\n1190: +        terminal = Terminal(connection, logger)\n1191: +        commander = FOSCommander(terminal, logger)\n1192: +        credentials = Credentials(\"admin\", \"oldpass\")\n1193: +        driver = FOSCliDriver(\n1194: +            terminal, commander, credentials, logger, \"bootstrap\",\n1195: +            MagicMock(), MagicMock(), allow_credential_recovery=True,\n1196: +        )\n1197: +\n\n(Output capped at 50 KB. Showing lines 1-1197. Use offset=1198 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\nindex ea16d0f..1af3f4d 100644\n--- a/fortinet/common/cli_commands.py\n+++ b/fortinet/common/cli_commands.py\n@@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n     CONTINUE = auto()\n     VALIDATE = auto()\n     FAIL = auto()\n \n \n+class ContextLossAction(Enum):\n+    RESTART_BLOCK = auto()\n+    FAIL = auto()\n+\n+\n @dataclass(frozen=True, init=False)\n class CommandSpec:\n     line: str\n     completion_states: tuple = ()\n     capture_output: bool = False",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\nindex ea16d0f..1af3f4d 100644\n--- a/fortinet/common/cli_commands.py\n+++ b/fortinet/common/cli_commands.py\n@@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n     CONTINUE = auto()\n     VALIDATE = auto()\n     FAIL = auto()\n \n \n+class ContextLossAction(Enum):\n+    RESTART_BLOCK = auto()\n+    FAIL = auto()\n+\n+\n @dataclass(frozen=True, init=False)\n class CommandSpec:\n     line: str\n     completion_states: tuple = ()\n     capture_output: bool = False\n     suppress_output: bool = False\n     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n     expected_completion_state: object = None\n     fail_on_error: bool = False\n+    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n+    continuation: bool = False\n \n     def __init__(self, line, completion_states=(), capture_output=False,\n                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n-                 expected_completion_state=None, fail_on_error=False):\n+                 expected_completion_state=None, fail_on_error=False,\n+                 context_loss=None, continuation=False):\n         object.__setattr__(self, \"line\", line)\n         object.__setattr__(self, \"completion_states\", completion_states)\n         object.__setattr__(self, \"capture_output\", capture_output)\n         object.__setattr__(self, \"suppress_output\", suppress_output)\n         object.__setattr__(self, \"session_loss\", session_loss)\n         object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n         object.__setattr__(self, \"fail_on_error\", fail_on_error)\n+        object.__setattr__(self, \"continuation\", continuation)\n+        if context_loss is None:\n+            # Commands that must not replay after logout must not replay after\n+            # an unexpected scope exit either. Features can override this policy.\n+            context_loss = (\n+                ContextLossAction.RESTART_BLOCK\n+                if session_loss == SessionLossAction.RESTART_BLOCK\n+                else ContextLossAction.FAIL\n+            )\n+        object.__setattr__(self, \"context_loss\", context_loss)\n         self.__post_init__()\n \n     def __post_init__(self):\n         if \"\\r\" in self.line or \"\\n\" in self.line:\n             raise ValueError(\"CLI commands must contain exactly one line\")\n \n+    @property\n+    def closes_scope(self):\n+        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n+\n \n @dataclass\n class CommandAttempt:\n     spec: CommandSpec\n     number: int\n     session_epoch: int\n     output: bytearray = field(default_factory=bytearray)\n+    prompt_context_before: tuple | None = None\n+    prompt_context_after: tuple | None = None\n+    block_index: int | None = None\n+    retry_count: int = 0\n \n     def on_output(self, output):\n-        if not self.spec.capture_output:\n+        if not (self.spec.capture_output or self.spec.closes_scope):\n             return False\n         data = bytes(output)\n         self.output.extend(data)\n         output.discard(data)\n         return True\n@@ -69,11 +95,11 @@ class Scope:\n     @property\n     def close_line(self):\n         raise NotImplementedError\n \n     def flatten(self):\n-        commands = [CommandSpec(self.open_line)]\n+        commands = flatten_commands(self.open_line)\n         for child in self.children:\n             commands.extend(flatten_commands(child))\n         commands.append(CommandSpec(self.close_line))\n         return commands\n \n@@ -107,49 +133,43 @@ class SetValue:\n         self.fail_on_error = fail_on_error\n         self.validate_prompt = validate_prompt\n \n     def flatten(self):\n         lines = str(self.value).strip().splitlines() or [\"\"]\n-        if len(lines) == 1:\n-            return [CommandSpec(\n-                f'set {self.field} \"{lines[0]}\"',\n-                capture_output=True,\n-                expected_completion_state=(\n-                    FOSCliState.CMD_PROMPT if self.validate_prompt else None\n-                ),\n-                fail_on_error=self.fail_on_error,\n-            )]\n-\n-        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n-        commands = [CommandSpec(\n-            f'set {self.field} \"{lines[0]}',\n-            completion_states=both_prompts,\n-            capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n-        )]\n-        commands.extend(CommandSpec(\n-            line,\n-            completion_states=both_prompts,\n-            capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n-        ) for line in lines[1:-1])\n+        lines[0] = f'set {self.field} \"{lines[0]}'\n+        lines[-1] += '\"'\n+        return _flatten_quoted_lines(\n+            lines, fail_on_error=self.fail_on_error,\n+            validate_prompt=self.validate_prompt,\n+        )\n+\n+\n+def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n+    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n+    commands = []\n+    for index, line in enumerate(lines):\n+        last_line = index == len(lines) - 1\n+        expected = (\n+            FOSCliState.CMD_PROMPT if last_line\n+            else FOSCliState.MULTILINE_PROMPT\n+        )\n+        completion_states = ()\n+        if len(lines) > 1:\n+            completion_states = (\n+                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n+                if last_line else\n+                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n+            )\n         commands.append(CommandSpec(\n-            f'{lines[-1]}\"',\n-            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),\n+            line,\n+            completion_states=completion_states,\n             capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.CMD_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n+            expected_completion_state=expected if validate_prompt else None,\n+            fail_on_error=fail_on_error,\n+            continuation=index > 0,\n         ))\n-        return commands\n+    return commands\n \n \n class CommandSequence:\n     \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n \n@@ -165,10 +185,12 @@ class CommandSequence:\n \n \n def flatten_commands(value):\n     \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n     if isinstance(value, str):\n+        if \"\\n\" in value:\n+            return _flatten_quoted_lines(value.split(\"\\n\"))\n         return [CommandSpec(value)]\n     if isinstance(value, CommandSpec):\n         return [value]\n     if isinstance(value, (Scope, CommandSequence, SetValue)):\n         return value.flatten()\ndiff --git a/fortinet/common/common.py b/fortinet/common/common.py\nindex 4ffb817..b020deb 100644\n--- a/fortinet/common/common.py\n+++ b/fortinet/common/common.py\n@@ -21,10 +21,11 @@ class FOSCliState(IntEnum):\n     CURRENT_PASSWORD = auto()\n     CONFIRMATION = auto()\n     CHANGE_PASSWORD_CONFIRM = auto()\n     MORE_PROMPT = auto()\n     MULTILINE_PROMPT = auto()\n+    KERNEL_PANIC = auto()\n     UNKNOWN = auto()  # Non-patterns from here on.\n     TN_TIMEOUT = auto()\n \n \n GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n@@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n )\n FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n+FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n+    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n+    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n+)\n \n DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n DEFAULT_USERNAME = \"admin\"\n DEFAULT_PASSWORD = DEFAULT_USERNAME\n \ndiff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\nindex 83ebc9b..5dd906a 100644\n--- a/fortinet/common/features/base.py\n+++ b/fortinet/common/features/base.py\n@@ -53,10 +53,14 @@ class Feature:\n         self.commander.feature_complete(self)\n \n     def on_session_loss(self, attempt):\n         return attempt.spec.session_loss\n \n+    def on_context_loss(self, attempt):\n+        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n+        return attempt.spec.context_loss\n+\n     def reversal_blocks(self):\n         \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n         return []\n \n     def undo(self):\ndiff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\nindex b8bc7de..af39225 100644\n--- a/fortinet/common/features/credentials.py\n+++ b/fortinet/common/features/credentials.py\n@@ -1,14 +1,15 @@\n \"\"\"Administrator bootstrap feature.\"\"\"\n \n-from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n+from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n+from ..common import FOSCliState\n \n from .base import StaticFeature\n \n \n class CredentialsFeature(StaticFeature):\n-    \"\"\"Configure the administrator and change credentials after password loss.\"\"\"\n+    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n \n     def __init__(self, vm, commander):\n         self._activate_after_admin_commit = False\n         self._desired_credentials_activated = False\n         self._password_change_committed = False\n@@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):\n                 fail_on_error=True,\n             ))\n         super().__init__(vm, commander, \"admin\", [\n             ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n             ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n+            CommandSequence(\"admin-relogin\", [CommandSpec(\n+                \"exit\",\n+                session_loss=SessionLossAction.CONTINUE,\n+                capture_output=True,\n+                fail_on_error=True,\n+                # A successful logout takes the session-loss path. Returning\n+                # straight to a CLI prompt must not count as verification.\n+                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n+            )]),\n         ], on_complete=lambda: self._activate_desired_credentials())\n \n+    def on_command_dispatched(self, attempt):\n+        if attempt.spec.line == \"exit\":\n+            self._activate_desired_credentials()\n+        super().on_command_dispatched(attempt)\n+\n     def on_session_loss(self, attempt):\n+        if attempt.spec.line == \"exit\":\n+            # The commander resumes this block only at the authenticated CLI\n+            # prompt. Clear the logout command so it cannot be replayed.\n+            return SessionLossAction.CONTINUE\n         if self._is_password_command(attempt.spec.line):\n             self._activate_desired_credentials()\n             self._activate_after_admin_commit = False\n             return SessionLossAction.CONTINUE\n+        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n+            # Some releases log out during the commit instead of returning\n+            # its CLI prompt. Authenticate with the committed password.\n+            self._activate_desired_credentials()\n+            self._activate_after_admin_commit = False\n+            self._password_change_committed = True\n+            return SessionLossAction.CONTINUE\n         if self._password_change_committed:\n             # FortiOS may log out as the admin edit closes. The password\n             # command and `next` have already committed the new credentials,\n             # so replaying this block would use the previous password again.\n             return SessionLossAction.CONTINUE\ndiff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\nindex 96a90d3..a5f0de7 100644\n--- a/fortinet/common/features/pki.py\n+++ b/fortinet/common/features/pki.py\n@@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):\n     @staticmethod\n     def _config_item_block(scope, name, children):\n         # A configuration attempt is deliberately best-effort: the feature\n         # must be able to inspect the result and fall back to the TFTP import\n         # path when a firmware release does not expose this config tree.  If\n-        # these wrapper commands keep ``fail_on_error`` enabled, the commander\n-        # raises before ``on_command_executed`` can record the failed config\n-        # attempt and select the fallback.\n+        # opening commands keep ``fail_on_error`` enabled, the commander raises\n+        # before ``on_command_executed`` can select that fallback. A return-code\n+        # failure from `next` or `end` is always fatal to the feature: the\n+        # commander checks scope commits even when fail_on_error is disabled.\n         def config_command(line):\n             return CommandSpec(line, capture_output=True, fail_on_error=False)\n \n         return CommandSequence(f\"{scope}-{name}\", [\n             config_command(f\"config {scope}\"),\ndiff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\nindex e404fc8..cb99aa4 100644\n--- a/fortinet/common/features/startup_config.py\n+++ b/fortinet/common/features/startup_config.py\n@@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):\n             \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n         )\n     return filtered\n \n \n+def _startup_config_commands(config):\n+    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n+    pending = []\n+    quote = None\n+    start_line = None\n+    for number, raw_line in enumerate(config, start=1):\n+        # Text mode normalizes file line endings. Only remove the delimiter;\n+        # whitespace and comment/scope-looking lines inside quotes are data.\n+        line = raw_line.removesuffix(\"\\n\")\n+        if not pending:\n+            line = line.lstrip()\n+            if not line or line.startswith(\"#\"):\n+                continue\n+            start_line = number\n+\n+        escaped = False\n+        for character in line:\n+            if escaped:\n+                escaped = False\n+            elif character == \"\\\\\":\n+                escaped = True\n+            elif character == quote:\n+                quote = None\n+            elif quote is None and character in {\"'\", '\"'}:\n+                quote = character\n+\n+        if quote is not None or escaped:\n+            pending.append(line)\n+            continue\n+        pending.append(line.rstrip())\n+        yield \"\\n\".join(pending)\n+        pending.clear()\n+\n+    if pending:\n+        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n+        raise ValueError(\n+            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n+        )\n+\n+\n def parse_startup_config(path):\n     roots = []\n     stack = []\n     with open(path) as config:\n-        for raw_line in config:\n-            line = raw_line.strip()\n-            if not line or line.startswith(\"#\"):\n-                continue\n+        for line in _startup_config_commands(config):\n             if line.startswith(\"config \"):\n                 node = ConfigBlock(line[7:])\n                 (stack[-1].children if stack else roots).append(node)\n                 stack.append(node)\n             elif line.startswith(\"edit \"):\ndiff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\nindex fa34100..b527816 100644\n--- a/fortinet/common/fos_cli_driver.py\n+++ b/fortinet/common/fos_cli_driver.py\n@@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10\n EXPECT_TIMEOUT_SECONDS = 1\n UNKNOWN_STALL_SECONDS = 30\n UNKNOWN_STALL_NEWLINE_LIMIT = 3\n \n \n+class KernelPanicError(RuntimeError):\n+    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n+\n+\n class FOSCliDriver:\n     \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n \n     def __init__(\n         self,\n@@ -65,10 +69,11 @@ class FOSCliDriver:\n             FOSCliState.CMD_PROMPT: self._command_prompt,\n             FOSCliState.CMD_PROMPT_ECHO: None,\n             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n             FOSCliState.LIC_FAIL: self._license_failed,\n             FOSCliState.TN_TIMEOUT: self._timeout,\n+            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n             FOSCliState.UNKNOWN: self._unknown,\n         }\n \n     @property\n     def state_patterns(self):\n@@ -145,11 +150,14 @@ class FOSCliDriver:\n \n     def _next_state(self):\n         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n         if match:\n             return FOSCliState(index), output, True\n-        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False\n+        # A timeout exposes retained bytes too. Only fresh input should reset\n+        # the unknown-output stall timer; an unchanged buffer is still idle.\n+        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n+        return state, output, False\n \n     def _handle_state(self, state):\n         handler = self._state_handlers.get(state)\n         if handler:\n             try:\n@@ -254,10 +262,14 @@ class FOSCliDriver:\n \n     def _unknown(self):\n         if self._last_known_state == FOSCliState.REBOOTING:\n             self._idle_spins += 1\n \n+    @staticmethod\n+    def _kernel_panic():\n+        raise KernelPanicError(\"Kernel panic detected on serial console\")\n+\n     def _note_unknown_output(self):\n         self._unknown_started_at = time.monotonic()\n \n     def _recover_unknown_stall(self):\n         if self._unknown_started_at is None:\ndiff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\nindex 26312cf..86b1be6 100644\n--- a/fortinet/common/fos_commander.py\n+++ b/fortinet/common/fos_commander.py\n@@ -10,24 +10,29 @@ from .cli_commands import (\n     CleanupAction,\n     CommandAttempt,\n     CommandSequence,\n     CommandSpec,\n     ConfigBlock,\n+    ContextLossAction,\n     SessionLossAction,\n     flatten_commands,\n )\n from .terminal import Data\n-from .common import FOSCliState, TRACE_LEVEL\n+from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n \n DISPATCHABLE_COMPLETION_STATES = {\n     FOSCliState.CMD_PROMPT,\n     FOSCliState.CONFIRMATION,\n     FOSCliState.MULTILINE_PROMPT,\n }\n COMMAND_FAILURE_PATTERN = re.compile(\n     rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n )\n+CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n+    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n+    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n+)\n \n \n @dataclass\n class _StandardOutputContext:\n     feature: object\n@@ -35,10 +40,11 @@ class _StandardOutputContext:\n     phase: str = \"inspect\"\n     restore: bool = False\n \n \n class FOSCommander:\n+    MAX_COMMAND_RECOVERY_RETRIES = 1\n     _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n     _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n     _CONSOLE_STANDARD_LINE = \"set output standard\"\n \n     def __init__(self, terminal, logger, continue_on_error=False):\n@@ -65,23 +71,37 @@ class FOSCommander:\n         self._start_time = datetime.datetime.now()\n         self._continue_on_error = continue_on_error\n         self._pending_feature_error = None\n         self._current_state = None\n         self._callback_failed = False\n+        self._prompt_context = None\n+        self._block_prompt_context = None\n+        self._recovery_retries = {}\n+        self._cleanup_retries = {}\n+        self._replay_context_target = None\n+        self._context_reset_attempted = False\n+        self._in_context_reset = False\n \n     def _call_feature(self, callback, *args):\n         \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n         try:\n             return callback(*args)\n         except Exception as error:\n-            if not self._continue_on_error:\n-                raise\n-            self.logger.exception(\"Bootstrap feature callback failed\")\n-            self._pending_feature_error = error\n-            self._callback_failed = True\n+            self._handle_work_error(error, from_callback=True)\n             return None\n \n+    def _handle_work_error(self, error, *, from_callback=False):\n+        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n+        if not self._continue_on_error:\n+            raise error\n+        if from_callback:\n+            self.logger.exception(\"Bootstrap feature callback failed\")\n+        else:\n+            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n+        self._pending_feature_error = error\n+        self._callback_failed = True\n+\n     def _recover_feature_error(self, *, at_idle_prompt=False):\n         error = self._pending_feature_error\n         if error is None or (\n             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n         ):\n@@ -143,10 +163,13 @@ class FOSCommander:\n             self._inflight = None\n             self._suppression.close()\n             self._suppression = ExitStack()\n \n         self._in_cleanup = False\n+        self._replay_context_target = None\n+        self._in_context_reset = False\n+        self._cleanup_retries.clear()\n         self._feature_errors.append((failed_name, str(error)))\n         return failed_name\n \n     def record_feature_error(self, name, error):\n         \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n@@ -184,10 +207,14 @@ class FOSCommander:\n         if self.busy:\n             raise RuntimeError(\"Cannot replace an active command block\")\n         commands = tuple(flatten_commands(block))\n         self._active_commands = commands\n         self._pending = deque(commands)\n+        self._block_prompt_context = self._prompt_context\n+        self._recovery_retries = {}\n+        self._replay_context_target = None\n+        self._context_reset_attempted = False\n \n     def feature_complete(self, feature):\n         if feature is not self._active_feature:\n             return\n         if self.busy:\n@@ -242,10 +269,18 @@ class FOSCommander:\n \n     def on_state(self, state, output):\n         \"\"\"Called by the driver for every recognized serial state.\"\"\"\n         self._current_state = state\n         self._callback_failed = False\n+        if state == FOSCliState.CMD_PROMPT:\n+            context = self._extract_prompt_context(output)\n+            if context is not None:\n+                self._prompt_context = context\n+            # Some releases return directly to a usable prompt after login,\n+            # without a Welcome banner. The prompt also ends session recovery.\n+            self._authenticated_once = True\n+            self._recovering = False\n         if self._pending_feature_error is not None:\n             if state == FOSCliState.CMD_PROMPT:\n                 self._recover_feature_error()\n             elif state == FOSCliState.SESSION_LOST:\n                 self._session_epoch += 1\n@@ -275,13 +310,10 @@ class FOSCommander:\n             return\n         if state == FOSCliState.CREDENTIAL_ACCEPTED:\n             self._authenticated_once = True\n             self._recovering = False\n             return\n-        if state == FOSCliState.CMD_PROMPT:\n-            self._authenticated_once = True\n-\n         if self._inflight and state in (\n             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n         ):\n             self._complete_inflight(state)\n             return\n@@ -345,28 +377,41 @@ class FOSCommander:\n         self._call_feature(self._active_feature.begin_activation)\n         if self._pending_feature_error is None:\n             self._call_feature(self._active_feature.activate)\n \n     def _dispatch_next(self):\n-        if self._inflight or self._recovering:\n+        if self._inflight or self._recovering or self._pending_feature_error is not None:\n+            return\n+        if not self._restore_replay_context():\n             return\n         if not self._cleanup and self._active_feature is None:\n             self._activate_next_feature()\n             if self._active_feature is None:\n                 return\n         if self._cleanup:\n             spec = self._cleanup.popleft()\n             self._in_cleanup = True\n+            block_index = None\n         elif not self._pending:\n             self._call_feature(self._active_feature.on_block_complete)\n             return\n         else:\n             spec = self._pending.popleft()\n             self._in_cleanup = False\n+            block_index = len(self._active_commands) - len(self._pending) - 1\n+        self._dispatch_command(spec, block_index)\n+\n+    def _dispatch_command(self, spec, block_index=None):\n         self._attempt_number += 1\n         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n-        if self._active_feature:\n+        self._inflight.prompt_context_before = self._prompt_context\n+        self._inflight.block_index = block_index\n+        self._inflight.retry_count = (\n+            self._cleanup_retries.get(id(spec), 0)\n+            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n+        )\n+        if self._active_feature and not self._in_context_reset:\n             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n             if self._pending_feature_error is not None:\n                 return\n         if spec.suppress_output:\n             self._suppression.enter_context(self.terminal.suppress_output())\n@@ -380,12 +425,34 @@ class FOSCommander:\n     def _complete_inflight(self, state):\n         attempt = self._inflight\n         self._inflight = None\n         self._suppression.close()\n         self._suppression = ExitStack()\n-        self._validate_completion(attempt, state)\n+        attempt.prompt_context_after = self._prompt_context\n+        if self._in_context_reset:\n+            self._in_context_reset = False\n+            self._dispatch_next()\n+            return\n+        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n+            self._handle_context_loss(attempt)\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            else:\n+                self._dispatch_next()\n+            return\n+        try:\n+            self._validate_completion(attempt, state)\n+        except RuntimeError as error:\n+            if state != FOSCliState.CMD_PROMPT:\n+                # An interactive prompt cannot safely advance to another feature.\n+                raise\n+            self._handle_work_error(error)\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            return\n         if self._in_cleanup:\n+            self._cleanup_retries.pop(id(attempt.spec), None)\n             self._in_cleanup = False\n             self._dispatch_next()\n             return\n         if self._is_standard_output_command(attempt.spec):\n             self._complete_standard_output_command(attempt)\n@@ -404,24 +471,105 @@ class FOSCommander:\n         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n             self._dispatch_next()\n \n     @staticmethod\n     def _validate_completion(attempt, state):\n-        if attempt.spec.fail_on_error and (\n+        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n         ):\n             raise RuntimeError(\n-                \"FortiOS command failed \"\n+                f\"FortiOS command {attempt.spec.line!r} failed \"\n                 f\"(return code {failure.group(1).decode()})\"\n             )\n         expected = attempt.spec.expected_completion_state\n         if expected is not None and state != expected:\n             raise RuntimeError(\n                 \"CLI command completed at unexpected prompt: \"\n                 f\"expected {expected.name}, received {state.name}\"\n             )\n \n+    def _prompt_context_changed(self, attempt):\n+        before = attempt.prompt_context_before\n+        after = attempt.prompt_context_after\n+        return (\n+            before is not None\n+            and after is not None\n+            and before != after\n+            and not self._command_may_change_context(attempt.spec)\n+        )\n+\n+    def _handle_context_loss(self, attempt):\n+        reason = (\n+            \"CLI context changed from \"\n+            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n+            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n+        )\n+        if self._in_cleanup:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n+            ))\n+            return\n+        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n+        if self._pending_feature_error is not None:\n+            return\n+        if action == ContextLossAction.RESTART_BLOCK:\n+            self._restart_active_block(attempt, reason)\n+        elif action == ContextLossAction.FAIL:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n+            ))\n+        else:\n+            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n+\n+    def _restore_replay_context(self):\n+        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n+        target = self._replay_context_target\n+        if target is None:\n+            return True\n+        if self._prompt_context == target:\n+            self._replay_context_target = None\n+            return True\n+        if self._context_reset_attempted:\n+            self._handle_work_error(RuntimeError(\n+                \"Unable to restore CLI context before replay: expected \"\n+                f\"{self._format_prompt_context(target)}, received \"\n+                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n+            ))\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            return False\n+        self._context_reset_attempted = True\n+        self._in_context_reset = True\n+        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n+        return False\n+\n+    @staticmethod\n+    def _command_may_change_context(spec):\n+        if spec.continuation:\n+            return False\n+        command = spec.line.strip().lower()\n+        return (\n+            command.startswith((\"config \", \"edit \"))\n+            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n+            or command == \"set vdom-mode multi-vdom\"\n+        )\n+\n+    @staticmethod\n+    def _extract_prompt_context(output):\n+        data = bytes(output)\n+        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n+        if not matches:\n+            return None\n+        return tuple(\n+            item.decode(errors=\"replace\")\n+            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n+        )\n+\n+    @staticmethod\n+    def _format_prompt_context(context):\n+        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n+\n     def _is_standard_output_command(self, spec):\n         context = self._standard_output_context\n         return context is not None and (\n             spec.line == self._CONSOLE_INSPECT_LINE\n             or (context.phase == \"set-standard\" and not self._pending)\n@@ -466,11 +614,24 @@ class FOSCommander:\n             return\n         attempt = self._inflight\n         self._inflight = None\n         self._suppression.close()\n         self._suppression = ExitStack()\n+        if self._in_context_reset:\n+            # Login may itself restore the target scope. The pending replay\n+            # stays bounded by the original command's recovery allowance.\n+            self._in_context_reset = False\n+            return\n         if self._in_cleanup:\n+            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n+            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n+                self._handle_work_error(RuntimeError(\n+                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n+                    \"retry limit reached\"\n+                ))\n+                return\n+            self._cleanup_retries[id(attempt.spec)] = retries + 1\n             self._cleanup.appendleft(attempt.spec)\n             self._in_cleanup = False\n             return\n         self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n         action = self._call_feature(\n@@ -481,24 +642,39 @@ class FOSCommander:\n             return\n         self.logger.info(\n             f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n         )\n         action_handlers = {\n-            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),\n+            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n+                attempt, \"session lost\"\n+            ),\n             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n             SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n-            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),\n+            SessionLossAction.FAIL: lambda: self._handle_work_error(\n+                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n+            ),\n             SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n         }\n         action_handlers[action]()\n \n-    def _restart_active_block(self):\n+    def _restart_active_block(self, attempt, reason):\n+        retries = self._recovery_retries.get(attempt.block_index, 0)\n+        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n+                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n+            ))\n+            return\n+        self._recovery_retries[attempt.block_index] = retries + 1\n         self._pending = deque(self._active_commands)\n-\n-    @staticmethod\n-    def _raise_session_loss(attempt):\n-        raise RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n+        self._replay_context_target = self._block_prompt_context\n+        self._context_reset_attempted = False\n+        self.logger.warning(\n+            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n+            reason, self._active_feature.name, attempt.spec.line,\n+            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n+        )\n \n     def enqueue_runtime_feature(self, feature):\n         return self.enqueue_runtime_features([feature])\n \n     def enqueue_runtime_features(self, features):\ndiff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\nindex 4c2d808..3c112e1 100755\n--- a/fortinet/common/launch.py\n+++ b/fortinet/common/launch.py\n@@ -30,11 +30,11 @@ from .features import (\n     InstallPkiCertificates,\n     ApplyStartupConfig,\n     ValidateProduct,\n )\n from .env import get_env\n-from .fos_cli_driver import FOSCliDriver\n+from .fos_cli_driver import FOSCliDriver, KernelPanicError\n from .fos_commander import FOSCommander\n from .host_forwarded_bridge import HostForwardedBridge\n from .net_mgmt_strategy import NetMgmtStrategy\n from .passthrough_redirect import PassthroughRedirect\n from .terminal import Terminal\n@@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):\n         \"\"\"\n         if self._bootstrap_error is not None:\n             return False\n         try:\n             self.driver.process_state()\n+        except KernelPanicError:\n+            self.stop()\n+            raise\n         except Exception as error:\n             if self._exit_on_bootstrap_error or self.commander.startup_complete:\n                 self.stop()\n                 raise\n             failed_work = self.commander.continue_after_error(\ndiff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\nindex 368238c..d124474 100644\n--- a/fortinet/common/terminal.py\n+++ b/fortinet/common/terminal.py\n@@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():\n \n \n class Data:\n     \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n \n-    def __init__(self, value, discard_callback=None):\n+    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n         self.value = bytes(value)\n         self._discard_callback = discard_callback\n         self.discarded = False\n+        self.received_new_data = (\n+            bool(self.value) if received_new_data is None else received_new_data\n+        )\n \n     def __bytes__(self):\n         return self.value\n \n     def __bool__(self):\n@@ -213,36 +216,46 @@ class Terminal:\n     def expect(self, regex_list, timeout=None):\n         \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n \n         The match ending earliest in the buffered stream wins. Data through that\n         match is returned and discarded; data after it remains buffered.\n+        On timeout, the entire unmatched buffer is returned for inspection and\n+        stays buffered unless the caller explicitly discards it.\n         \"\"\"\n         self._ensure_reader()\n         deadline = None if timeout is None else time.monotonic() + timeout\n-        received = bytearray()\n+        received_new_data = False\n         result = self._match(regex_list)\n \n         while result is None:\n             remaining = None if deadline is None else deadline - time.monotonic()\n             if remaining is not None and remaining <= 0:\n-                return -1, None, Data(bytes(received), self._discard_prefix)\n+                return -1, None, Data(\n+                    self._buffer,\n+                    self._discard_prefix,\n+                    received_new_data=received_new_data,\n+                )\n \n             data = self._read_queue.get(remaining)\n             if data:\n                 self._buffer.extend(data)\n                 self._enforce_buffer_limit()\n-                received.extend(data)\n+                received_new_data = True\n                 if (\n                     get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n                     and self._output_suppression_depth == 0\n                 ):\n-                    self._logger.log(TRACE_LEVEL - 1, f\"buffer: {self._buffer}\")\n+                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n                 result = self._match(regex_list)\n                 continue\n \n             if deadline is not None and time.monotonic() >= deadline:\n-                return -1, None, Data(bytes(received), self._discard_prefix)\n+                return -1, None, Data(\n+                    self._buffer,\n+                    self._discard_prefix,\n+                    received_new_data=received_new_data,\n+                )\n \n         index, match = result\n         consumed = bytes(self._buffer[:match.end()])\n         stable_match = re.search(regex_list[index], consumed)\n         del self._buffer[:match.end()]\n@@ -251,11 +264,14 @@ class Terminal:\n     def _discard_prefix(self, data):\n         \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n         if not data:\n             return\n         if not self._buffer.startswith(data):\n-            self._logger.debug(\"Refusing to discard non-prefix terminal output\")\n+            message = \"Refusing to discard non-prefix terminal output\"\n+            if self._logger.isEnabledFor(TRACE_LEVEL):\n+                message += f\": data={data!r}; buffer={self._buffer!r}\"\n+            self._logger.warning(message)\n             return\n         del self._buffer[:len(data)]\n \n     def _enforce_buffer_limit(self):\n         if len(self._buffer) <= self._buffer_limit:\ndiff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\nindex 1d95aea..37c576e 100644\n--- a/fortinet/fortigate/README.md\n+++ b/fortinet/fortigate/README.md\n@@ -167,11 +167,15 @@ config system global\n     set alias \"lab-fgt\"\n end\n ```\n \n The importer validates basic `config` / `edit` / `next` / `end` nesting and\n-fails startup on malformed structure.\n+fails startup on malformed structure or unterminated quoted strings. Single-\n+and double-quoted values can span lines. Newlines, whitespace, blank lines,\n+and scope keywords inside a quoted value are preserved. Each continued line\n+is sent only after the CLI's continuation prompt; the closing line must return\n+to a command prompt. An unexpected prompt follows the bootstrap error policy.\n \n The bootstrap DNS servers selected from the container resolver or\n `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\ndiff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\nindex 9e11b86..74a118d 100644\n--- a/fortinet/fortigate/docker/README.md\n+++ b/fortinet/fortigate/docker/README.md\n@@ -35,12 +35,15 @@ Important behavior:\n - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n   writing to the serial connection directly. The writer preserves write order\n   and sends one queued chunk at a time, so commander/driver state handling is\n   not paced by each scrapli write call.\n - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n-  view of what was just read or matched, and timeout `Data` can discard bytes\n-  from the terminal's retained buffer.\n+  view of the matched prefix or, on timeout, the entire unmatched buffer.\n+  Inspecting timeout `Data` leaves those bytes buffered so later input can\n+  complete a partial token. Calling `discard()` explicitly consumes the view.\n+  `received_new_data` distinguishes fresh input from another inspection of the\n+  same retained bytes, so idle waits still advance the driver's stall timer.\n - When multiple regexes match buffered output, the match that ends earliest\n   wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n - Matched bytes are consumed from the buffer; bytes after the match stay queued\n   for the next state parse.\n - Timeout bytes are not consumed automatically. A command, feature, or commander\n@@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.\n The dispatcher sends one command at a time and waits for an appropriate state\n before continuing. By default, a command completes at the next command prompt.\n Some commands override completion states, for example confirmation prompts or\n reboot messages.\n \n+Scope-closing commands (`next` and `end`) always capture their output and check\n+for `Command fail. Return code <number>`, including builds that append a period\n+after the code. A closing failure stops the feature before completion callbacks\n+or further commands, even when `fail_on_error=False`. It follows the bootstrap\n+error policy: abort normally, or skip the failed feature when\n+`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n+individual `set` commands, which can deliberately tolerate unsupported fields.\n+\n Session loss is explicit. Each command carries a `SessionLossAction`:\n \n - `RESTART_BLOCK`: replay the current block from the start\n - `COMPLETE_BLOCK`: treat the block as complete\n - `CONTINUE`: do not replay the disruptive command\n - `VALIDATE`: reserve for commands that need post-loss validation\n-- `FAIL`: raise immediately\n+- `FAIL`: report failure through the configured bootstrap error policy\n \n This matters because commands such as license restore and password updates can\n drop the active admin session. Replaying them blindly can corrupt state or loop.\n \n+Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n+The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n+commands that allow session-loss replay also allow context-loss replay; commands\n+with another session-loss policy decline context-loss replay unless explicitly\n+configured otherwise. Context loss does not invoke session-loss callbacks, since\n+those may commit credential or licensing transitions.\n+\n+The commander allows one recovery per command position within a submitted block,\n+shared between context loss and session loss. Recovery replays the block's scope\n+openers and commands. If necessary, the commander sends one `abort` to restore\n+the block's initial prompt context before replay. A repeated loss at the same\n+command or failure to restore that context follows the bootstrap error policy.\n+The allowance resets when the feature submits a new block. Cleanup commands also\n+have one session-loss retry. Attempts expose `retry_count` and the prompt context\n+before and after execution so features can make their recovery decision.\n+\n The dispatcher also manages cleanup actions and standard-output contexts.\n Features can request console output mode `standard` for machine-readable output;\n the dispatcher detects the current console mode, changes it only when needed,\n and restores `more` after the feature completes.\n \n@@ -219,22 +246,23 @@ begin_activation()\n on_command_dispatched(attempt)\n on_output(output)\n on_command_executed(command, state)\n on_block_complete()\n on_session_loss(attempt)\n+on_context_loss(attempt)\n mark_completed()\n ```\n \n Static command features subclass `StaticFeature`; they submit a fixed list of\n blocks and complete after the last block. Dynamic features subclass `Feature`\n and submit follow-up blocks based on command output or timer ticks.\n \n Current bootstrap stages are:\n \n - `disk-format`: formats additional disks after the first FortiGate log disk\n-- `admin`: disables password policy, creates/updates the desired admin, and\n-  handles session loss during password changes\n+- `admin`: disables password policy, creates/updates the desired admin, then\n+  logs out and waits for console authentication before later stages run\n - `image-info`: reads `get system status` once and stores the parsed\n   platform, major, minor, patch, and build on `vm.fos_version` for later\n   features\n - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n   the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n@@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept\n a blank default password first. The driver keeps separate bootstrap and desired\n credentials so it can answer prompts with the password that is valid at that\n moment.\n \n The desired credentials are activated after the admin edit commits. Password\n-command output is checked for FortiOS command failures. After a password\n-change, the driver first tries the desired credentials. If FortiOS rejects\n+command output is checked for FortiOS command failures. After closing the admin\n+configuration, the feature sends `exit` and waits for a successful login and CLI\n+prompt before completing. A logout during the commit also activates the new\n+credentials without replaying the password change. The driver first tries the\n+desired credentials. If FortiOS rejects\n them, it retries immediately with the previously accepted credentials, without\n replacing the desired credentials used for later logins.\n \n ### Prompt patterns change during bootstrap\n \ndiff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\nnew file mode 100644\nindex 0000000..7dc469b\n--- /dev/null\n+++ b/fortinet/tests/test_common_admin_credentials.py\n@@ -0,0 +1,154 @@\n+\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from types import SimpleNamespace\n+from unittest.mock import MagicMock, patch\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.common import Credentials\n+from fortinet.common.features.credentials import CredentialsFeature\n+from fortinet.common.fos_cli_driver import FOSCliDriver\n+from fortinet.common.fos_commander import FOSCommander\n+from fortinet.common.terminal import Terminal\n+from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n+\n+\n+LOGIN = b\"fw login:\\r\\n\"\n+READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n+ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n+\n+\n+class AdminCredentialsTests(unittest.TestCase):\n+    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n+                   auto_logout=None, authenticate=True, reject=False,\n+                   exit_works=True):\n+        logger = MagicMock()\n+        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n+        old_password_responses = [READY]\n+        if password:\n+            old_password_responses.append(ADMIN_PROMPT)\n+        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n+        end_count = 0\n+\n+        def end_response():\n+            nonlocal end_count\n+            end_count += 1\n+            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n+\n+        login_reply = None if not authenticate else (\n+            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n+        )\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n+            b\"config system password-policy\\r\": policy_prompt,\n+            b\"set status disable\\r\": policy_prompt,\n+            b\"config system admin\\r\": ADMIN_PROMPT,\n+            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n+            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n+            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n+            b\"end\\r\": end_response,\n+            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n+            b\"probe\\r\": b\"fw #\\r\\n\",\n+            (password + \"\\r\").encode(): login_reply,\n+        }\n+        if username != \"admin\":\n+            responses[(username + \"\\r\").encode()] = b\"Password:\"\n+        if password:\n+            responses[f\"set password {password}\\r\".encode()] = (\n+                b\"Please enter current administrator password: \"\n+            )\n+        else:\n+            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n+\n+        connection = SerialConnection(responses)\n+        terminal = Terminal(connection, logger)\n+        commander = FOSCommander(terminal, logger)\n+        credentials = Credentials(\"admin\", \"oldpass\")\n+        driver = FOSCliDriver(\n+            terminal, commander, credentials, logger, \"bootstrap\",\n+            MagicMock(), MagicMock(), allow_credential_recovery=True,\n+        )\n+",
        "lineStart": 1,
        "lineEnd": 1197,
        "totalLines": 1198,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716198307,
      "end": 1793716198326
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d11bc8001Sz6V11XB5Y6Smi",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d114bf001b7PRnRynOkPtjP",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3563,
    "input": 3520,
    "output": 25,
    "reasoning": 18,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d114bf001b7PRnRynOkPtjP",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716196543,
    "completed": 1793716198347
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3563,
    "input": 3520,
    "output": 25,
    "reasoning": 18,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 4
step-start
{
  "type": "step-start",
  "id": "prt_1a1d1275e0013hOLtbs44WcVhN",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d11bcd001Vfv50xKiBoiGMh"
}
Reasoning
The diff is large. Let me continue reading diff.txt from offset 1198.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 1198,
  "limit": 1200
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1198: +        def activate_desired():
1199: +            driver.remember_current_credentials()
1200: +            credentials.username = username
1201: +            credentials.password = password
1202: +
1203: +        vm = SimpleNamespace(
1204: +            desired_credentials=Credentials(username, password),
1205: +            activate_desired_credentials=activate_desired,
1206: +        )
1207: +        admin = CredentialsFeature(vm, commander)
1208: +        following = RecordingFeature(commander, "following", ["probe"])
1209: +        commander.start([admin, following])
1210: +        self.addCleanup(lambda: terminal.close() if not connection.closed else None)
1211: +        return connection, commander, driver, admin, following
1212: +
1213: +    def run_driver(self, driver):
1214: +        with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
1215: +                patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.15):
1216: +            driver.process_state()
1217: +
1218: +    def test_logout_and_relogin_after_committing_credentials(self):
1219: +        for username, password in (("admin", "newpass"), ("admin", ""),
1220: +                                   ("operator", "newpass")):
1221: +            with self.subTest(username=username, password_set=bool(password)):
1222: +                conn, cmd, driver, admin, following = self.make_stack(
1223: +                    username=username, password=password,
1224: +                )
1225: +                self.run_driver(driver)
1226: +                self.assertTrue(cmd.ready)
1227: +                self.assertTrue(admin.completed)
1228: +                self.assertTrue(following.completed)
1229: +                logout = conn.writes.index(b"exit\r")
1230: +                self.assertEqual(conn.writes[logout - 1], b"end\r")
1231: +                self.assertEqual(conn.writes[logout + 1:], [
1232: +                    (username + "\r").encode(),
1233: +                    (password + "\r").encode(),
1234: +                    b"probe\r",
1235: +                ])
1236: +                self.assertEqual(conn.writes.count(b"exit\r"), 1)
1237: +
1238: +    def test_later_features_wait_for_authentication(self):
1239: +        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)
1240: +        self.run_driver(driver)
1241: +        self.assertIn(b"exit\r", conn.writes)
1242: +        self.assertIn(b"newpass\r", conn.writes)
1243: +        self.assertNotIn(b"probe\r", conn.writes)
1244: +        self.assertFalse(admin.completed)
1245: +        self.assertFalse(following.completed)
1246: +        self.assertFalse(cmd.ready)
1247: +
1248: +    def test_fortios_logout_at_commit_does_not_replay_password_change(self):
1249: +        for commit_command in ("next", "end"):
1250: +            with self.subTest(commit_command=commit_command):
1251: +                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)
1252: +                self.run_driver(driver)
1253: +                self.assertTrue(cmd.ready)
1254: +                self.assertTrue(admin.completed)
1255: +                self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
1256: +                self.assertEqual(conn.writes.count(b"exit\r"), 1)
1257: +                self.assertEqual(conn.writes.count(b"newpass\r"), 2)
1258: +
1259: +    def test_logout_must_return_to_login(self):
1260: +        conn, _, driver, admin, _ = self.make_stack(exit_works=False)
1261: +        with self.assertRaisesRegex(RuntimeError, "expected PROVIDE_USERNAME"):
1262: +            self.run_driver(driver)
1263: +        self.assertFalse(admin.completed)
1264: +        self.assertNotIn(b"probe\r", conn.writes)
1265: +
1266: +    def test_rejected_credentials_do_not_start_later_features(self):
1267: +        conn, _, driver, admin, _ = self.make_stack(reject=True)
1268: +        with self.assertRaisesRegex(RuntimeError, "Credential rejected"):
1269: +            self.run_driver(driver)
1270: +        self.assertFalse(admin.completed)
1271: +        self.assertNotIn(b"probe\r", conn.writes)
1272: +        self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
1273: +
1274: +
1275: +if __name__ == "__main__":
1276: +    unittest.main()
1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py
1278: new file mode 100644
1279: index 0000000..2afb43a
1280: --- /dev/null
1281: +++ b/fortinet/tests/test_common_recovery.py
1282: @@ -0,0 +1,292 @@
1283: +"""Bounded recovery after a scope exit or an interrupted CLI session."""
1284: +
1285: +import sys
1286: +import unittest
1287: +from pathlib import Path
1288: +from unittest.mock import MagicMock
1289: +
1290: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1291: +
1292: +from fortinet.common.cli_commands import (  # noqa: E402
1293: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,
1294: +    EditBlock, SessionLossAction,
1295: +)
1296: +from fortinet.common.common import FOSCliState  # noqa: E402
1297: +from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402
1298: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1299: +from fortinet.common.terminal import Data  # noqa: E402
1300: +
1301: +
1302: +IP_COMMAND = "set ip 10.0.52.4/24"
1303: +ACCESS_COMMAND = "set allowaccess ping https ssh http"
1304: +
1305: +
1306: +class RecordingFeature(Feature):
1307: +    def __init__(self, commander, block, context_action=None):
1308: +        super().__init__(None, commander, "management")
1309: +        self.block = block
1310: +        self.context_action = context_action
1311: +        self.losses = []
1312: +        self.attempts = []
1313: +        self.executed = []
1314: +
1315: +    def activate(self):
1316: +        self.commander.submit_block(self, self.block)
1317: +
1318: +    def on_command_dispatched(self, attempt):
1319: +        super().on_command_dispatched(attempt)
1320: +        self.attempts.append(attempt)
1321: +
1322: +    def on_command_executed(self, attempt, state):
1323: +        self.executed.append(attempt.spec.line)
1324: +
1325: +    def on_context_loss(self, attempt):
1326: +        self.losses.append(attempt)
1327: +        if self.context_action is not None:
1328: +            return self.context_action
1329: +        return super().on_context_loss(attempt)
1330: +
1331: +
1332: +class RecoveryTests(unittest.TestCase):
1333: +    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,
1334: +                       context_action=None, following=False):
1335: +        terminal = MagicMock()
1336: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error)
1337: +        block = ConfigBlock("system interface", [EditBlock("port1", [
1338: +            ip_command, ACCESS_COMMAND,
1339: +        ])])
1340: +        feature = RecordingFeature(commander, block, context_action)
1341: +        features = [feature]
1342: +        if following:
1343: +            features.append(RecordingFeature(
1344: +                commander, CommandSequence("following", ["get system status"])
1345: +            ))
1346: +        commander.start(features)
1347: +        return commander, terminal, feature
1348: +
1349: +    def prompt(self, commander, context=None):
1350: +        scope = f" ({context})" if context else ""
1351: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(
1352: +            f"FGT-VM64-KVM-NSVHDM{scope} (Interim)#".encode()
1353: +        ))
1354: +
1355: +    def enter_interface(self, commander):
1356: +        self.prompt(commander, "interface")
1357: +        self.prompt(commander, "port1")
1358: +
1359: +    def finish_interface(self, commander):
1360: +        self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
1361: +        self.prompt(commander, "port1")  # allowaccess succeeds; dispatch next.
1362: +        self.prompt(commander, "interface")  # next succeeds; dispatch end.
1363: +        self.prompt(commander)  # end succeeds.
1364: +
1365: +    @staticmethod
1366: +    def writes(terminal):
1367: +        return [call.args[0] for call in terminal.write.call_args_list]
1368: +
1369: +    def reconnect(self, commander):
1370: +        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b"Welcome!"))
1371: +        self.prompt(commander)
1372: +
1373: +    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):
1374: +        commander, terminal, feature = self.make_commander()
1375: +        self.prompt(commander)
1376: +        self.enter_interface(commander)
1377: +        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.
1378: +        self.assertEqual(self.writes(terminal), [
1379: +            "config system interface\r", "edit port1\r", IP_COMMAND + "\r",
1380: +            "config system interface\r",
1381: +        ])
1382: +        self.assertNotIn(IP_COMMAND, feature.executed)
1383: +        self.assertEqual(feature.losses[0].prompt_context_before, ("port1", "Interim"))
1384: +        self.assertEqual(feature.losses[0].prompt_context_after, ("Interim",))
1385: +        self.enter_interface(commander)
1386: +        self.finish_interface(commander)
1387: +        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]
1388: +        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])
1389: +        self.assertTrue(feature.completed)
1390: +        self.assertTrue(commander.ready)
1391: +
1392: +    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):
1393: +        for best_effort in (False, True):
1394: +            with self.subTest(best_effort=best_effort):
1395: +                commander, terminal, feature = self.make_commander(
1396: +                    continue_on_error=best_effort, following=True,
1397: +                )
1398: +                self.prompt(commander)
1399: +                self.enter_interface(commander)
1400: +                self.prompt(commander)
1401: +                self.enter_interface(commander)
1402: +                if best_effort:
1403: +                    self.prompt(commander)
1404: +                    self.assertIn("retry limit", commander.feature_errors[0][1])
1405: +                    self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1406: +                else:
1407: +                    with self.assertRaisesRegex(RuntimeError, "retry limit"):
1408: +                        self.prompt(commander)
1409: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
1410: +                self.assertNotIn(ACCESS_COMMAND + "\r", self.writes(terminal))
1411: +                self.assertFalse(feature.completed)
1412: +
1413: +    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):
1414: +        commander, terminal, feature = self.make_commander()
1415: +        self.prompt(commander)
1416: +        self.enter_interface(commander)
1417: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1418: +        self.reconnect(commander)
1419: +        self.enter_interface(commander)
1420: +        with self.assertRaisesRegex(RuntimeError, "retry limit"):
1421: +            self.prompt(commander)
1422: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
1423: +        self.assertEqual(feature.losses[0].retry_count, 1)
1424: +
1425: +    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):
1426: +        commander, terminal, _feature = self.make_commander(
1427: +            continue_on_error=True, following=True,
1428: +        )
1429: +        self.prompt(commander)
1430: +        self.enter_interface(commander)
1431: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1432: +        self.reconnect(commander)
1433: +        self.enter_interface(commander)
1434: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
1435: +        self.assertNotIn("get system status\r", self.writes(terminal))
1436: +        self.reconnect(commander)
1437: +        self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1438: +        self.assertIn("retry limit", commander.feature_errors[0][1])
1439: +
1440: +    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):
1441: +        commander, terminal, _feature = self.make_commander(
1442: +            continue_on_error=True, following=True,
1443: +        )
1444: +        self.prompt(commander)
1445: +        self.enter_interface(commander)
1446: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1447: +        self.prompt(commander)  # Successful login returns a prompt, no Welcome.
1448: +        self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
1449: +        self.enter_interface(commander)
1450: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
1451: +        self.assertNotIn("get system status\r", self.writes(terminal))
1452: +        self.prompt(commander)  # Exhaustion is handled at this usable prompt.
1453: +        self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1454: +        self.assertIn("retry limit", commander.feature_errors[0][1])
1455: +
1456: +    def test_each_command_position_gets_one_recovery(self):
1457: +        commander, terminal, feature = self.make_commander()
1458: +        self.prompt(commander)
1459: +        self.enter_interface(commander)
1460: +        self.prompt(commander)  # First loss: IP command.
1461: +        self.enter_interface(commander)
1462: +        self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
1463: +        self.prompt(commander)  # Second loss: allowaccess command.
1464: +        self.enter_interface(commander)
1465: +        self.finish_interface(commander)
1466: +        self.assertTrue(feature.completed)
1467: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 3)
1468: +        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + "\r"), 2)
1469: +
1470: +    def test_feature_can_decline_replay_without_running_session_loss_callback(self):
1471: +        for explicit_policy in (False, True):
1472: +            with self.subTest(explicit_policy=explicit_policy):
1473: +                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)
1474: +                commander, terminal, feature = self.make_commander(
1475: +                    ip_command=IP_COMMAND if explicit_policy else spec,
1476: +                    context_action=ContextLossAction.FAIL if explicit_policy else None,
1477: +                )
1478: +                feature.on_session_loss = MagicMock()
1479: +                self.prompt(commander)
1480: +                self.enter_interface(commander)
1481: +                with self.assertRaisesRegex(RuntimeError, "feature declined replay"):
1482: +                    self.prompt(commander)
1483: +                feature.on_session_loss.assert_not_called()
1484: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
1485: +
1486: +    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):
1487: +        spec = CommandSpec(
1488: +            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,
1489: +            context_loss=ContextLossAction.RESTART_BLOCK,
1490: +        )
1491: +        commander, _terminal, feature = self.make_commander(ip_command=spec)
1492: +        feature.on_session_loss = MagicMock()
1493: +        self.prompt(commander)
1494: +        self.enter_interface(commander)
1495: +        self.prompt(commander)
1496: +        self.enter_interface(commander)
1497: +        self.finish_interface(commander)
1498: +        self.assertTrue(feature.completed)
1499: +        feature.on_session_loss.assert_not_called()
1500: +
1501: +    def test_partial_scope_is_aborted_once_before_replay(self):
1502: +        commander, terminal, feature = self.make_commander()
1503: +        self.prompt(commander)
1504: +        self.enter_interface(commander)
1505: +        self.prompt(commander, "interface")  # Only the edit context disappeared.
1506: +        self.assertEqual(self.writes(terminal)[-1], "abort\r")
1507: +        self.prompt(commander)
1508: +        self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
1509: +        self.enter_interface(commander)
1510: +        self.finish_interface(commander)
1511: +        self.assertTrue(feature.completed)
1512: +        self.assertNotIn("abort", feature.executed)
1513: +        self.assertNotIn("abort", [item.spec.line for item in feature.attempts])
1514: +
1515: +    def test_failed_context_reset_does_not_loop(self):
1516: +        commander, terminal, _feature = self.make_commander()
1517: +        self.prompt(commander)
1518: +        self.enter_interface(commander)
1519: +        self.prompt(commander, "interface")
1520: +        with self.assertRaisesRegex(RuntimeError, "Unable to restore CLI context"):
1521: +            self.prompt(commander, "interface")
1522: +        self.assertEqual(self.writes(terminal).count("abort\r"), 1)
1523: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
1524: +
1525: +    def test_session_loss_during_context_reset_resumes_after_login(self):
1526: +        commander, terminal, feature = self.make_commander()
1527: +        self.prompt(commander)
1528: +        self.enter_interface(commander)
1529: +        self.prompt(commander, "interface")
1530: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1531: +        self.reconnect(commander)
1532: +        self.enter_interface(commander)
1533: +        self.finish_interface(commander)
1534: +        self.assertTrue(feature.completed)
1535: +        self.assertEqual(self.writes(terminal).count("abort\r"), 1)
1536: +
1537: +    def test_cleanup_session_loss_is_bounded(self):
1538: +        terminal = MagicMock()
1539: +        commander = FOSCommander(terminal, MagicMock())
1540: +        feature = RecordingFeature(commander, CommandSequence("work", ["get status"]))
1541: +        commander.register_cleanup(feature, CleanupAction(
1542: +            "cleanup", CommandSequence("cleanup", ["get cleanup"]),
1543: +        ))
1544: +        commander.start([feature])
1545: +        self.prompt(commander)
1546: +        self.prompt(commander)  # Begin cleanup after the feature completes.
1547: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1548: +        self.reconnect(commander)
1549: +        with self.assertRaisesRegex(RuntimeError, "retry limit"):
1550: +            commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1551: +        self.assertEqual(self.writes(terminal).count("get cleanup\r"), 2)
1552: +
1553: +    def test_newly_submitted_block_resets_retry_allowance(self):
1554: +        terminal = MagicMock()
1555: +        commander = FOSCommander(terminal, MagicMock())
1556: +        feature = StaticFeature(None, commander, "two-blocks", [
1557: +            ConfigBlock("system global", ["set alias first"]),
1558: +            ConfigBlock("system global", ["set alias second"]),
1559: +        ])
1560: +        commander.start([feature])
1561: +        self.prompt(commander)
1562: +        for _index in range(2):
1563: +            self.prompt(commander, "global")
1564: +            self.prompt(commander)  # Lost context: retry this block.
1565: +            self.prompt(commander, "global")
1566: +            self.prompt(commander, "global")
1567: +            self.prompt(commander)  # End this block and start the next one.
1568: +        self.assertTrue(feature.completed)
1569: +        self.assertEqual(self.writes(terminal).count("set alias first\r"), 2)
1570: +        self.assertEqual(self.writes(terminal).count("set alias second\r"), 2)
1571: +
1572: +
1573: +if __name__ == "__main__":
1574: +    unittest.main()
1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py
1576: new file mode 100644
1577: index 0000000..56ce729
1578: --- /dev/null
1579: +++ b/fortinet/tests/test_common_scope_errors.py
1580: @@ -0,0 +1,154 @@
1581: +"""Scope commit failures are mandatory errors, including best-effort commands."""
1582: +
1583: +import sys
1584: +import unittest
1585: +from pathlib import Path
1586: +from unittest.mock import MagicMock
1587: +
1588: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1589: +
1590: +from fortinet.common.cli_commands import (  # noqa: E402
1591: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,
1592: +)
1593: +from fortinet.common.common import FOSCliState  # noqa: E402
1594: +from fortinet.common.features.base import Feature  # noqa: E402
1595: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1596: +from fortinet.common.terminal import Data  # noqa: E402
1597: +
1598: +
1599: +class RecordingFeature(Feature):
1600: +    def __init__(self, commander, name, commands):
1601: +        super().__init__(None, commander, name)
1602: +        self.commands = commands
1603: +        self.executed = []
1604: +
1605: +    def activate(self):
1606: +        self.commander.submit_block(self, CommandSequence(self.name, self.commands))
1607: +
1608: +    def on_command_executed(self, attempt, state):
1609: +        self.executed.append(attempt.spec.line)
1610: +
1611: +
1612: +class ScopeCommitFailureTests(unittest.TestCase):
1613: +    @staticmethod
1614: +    def prompt(commander, context=None, output=b""):
1615: +        scope = f" ({context})" if context else ""
1616: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(
1617: +            output + f"fw{scope} #".encode()
1618: +        ))
1619: +
1620: +    @staticmethod
1621: +    def writes(terminal):
1622: +        return [call.args[0] for call in terminal.write.call_args_list]
1623: +
1624: +    def test_closing_failure_cannot_be_disabled_or_replayed(self):
1625: +        for close in ("next", "end"):
1626: +            for capture in (False, True):
1627: +                for best_effort in (False, True):
1628: +                    with self.subTest(close=close, capture=capture, best_effort=best_effort):
1629: +                        terminal = MagicMock()
1630: +                        commander = FOSCommander(terminal, MagicMock(), best_effort)
1631: +                        feature = RecordingFeature(commander, "commit", [
1632: +                            CommandSpec(close, capture_output=capture, fail_on_error=False),
1633: +                            "set must-not-run 1",
1634: +                        ])
1635: +                        feature.on_context_loss = MagicMock()
1636: +                        following = RecordingFeature(commander, "following", ["get status"])
1637: +                        commander.start([feature, following])
1638: +                        self.prompt(commander, "port1")
1639: +                        # The failure code can span multiple serial reads.
1640: +                        for chunk in (b"Command fa", b"il. Return co", b"de -542.\r\n"):
1641: +                            data = Data(chunk)
1642: +                            commander.on_output(data)
1643: +                            self.assertTrue(data.discarded)
1644: +                        if best_effort:
1645: +                            self.prompt(commander, "interface")
1646: +                            self.assertEqual(self.writes(terminal), [close + "\r", "get status\r"])
1647: +                            self.assertEqual(commander.feature_errors[0][0], "commit")
1648: +                            self.assertIn("return code -542", commander.feature_errors[0][1])
1649: +                        else:
1650: +                            with self.assertRaisesRegex(RuntimeError, "return code -542"):
1651: +                                self.prompt(commander, "interface")
1652: +                            self.assertEqual(self.writes(terminal), [close + "\r"])
1653: +                        feature.on_context_loss.assert_not_called()
1654: +                        self.assertEqual(feature.executed, [])
1655: +                        self.assertFalse(feature.completed)
1656: +
1657: +    def test_closing_failure_with_same_prompt_still_ejects(self):
1658: +        for code in ("0", "7", "-61"):
1659: +            for suffix in ("", "."):
1660: +                with self.subTest(code=code, suffix=suffix):
1661: +                    terminal = MagicMock()
1662: +                    commander = FOSCommander(terminal, MagicMock())
1663: +                    feature = RecordingFeature(commander, "commit", ["next", "end"])
1664: +                    commander.start([feature])
1665: +                    self.prompt(commander, "port1")
1666: +                    with self.assertRaisesRegex(RuntimeError, f"return code {code}"):
1667: +                        self.prompt(
1668: +                            commander, "port1",
1669: +                            f"  Command fail. Return code {code}{suffix}\r\n".encode(),
1670: +                        )
1671: +                    self.assertEqual(self.writes(terminal), ["next\r"])
1672: +
1673: +    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):
1674: +        for capture in (False, True):
1675: +            with self.subTest(capture=capture):
1676: +                terminal = MagicMock()
1677: +                commander = FOSCommander(terminal, MagicMock())
1678: +                feature = RecordingFeature(commander, "configure", [
1679: +                    ConfigBlock("system interface", [EditBlock("port1", [
1680: +                        CommandSpec("set unsupported 1", capture_output=capture),
1681: +                    ])]),
1682: +                ])
1683: +                commander.start([feature])
1684: +                self.prompt(commander)
1685: +                self.prompt(commander, "interface")
1686: +                self.prompt(commander, "port1")
1687: +                self.prompt(commander, "port1", b"Command fail. Return code -61.\r\n")
1688: +                self.assertEqual(self.writes(terminal)[-1], "next\r")
1689: +                self.prompt(commander, "interface")
1690: +                self.prompt(commander)
1691: +                self.assertTrue(feature.completed)
1692: +                self.assertTrue(commander.ready)
1693: +                self.assertEqual(commander.feature_errors, ())
1694: +
1695: +    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):
1696: +        for best_effort in (False, True):
1697: +            with self.subTest(best_effort=best_effort):
1698: +                terminal = MagicMock()
1699: +                commander = FOSCommander(terminal, MagicMock(), best_effort)
1700: +                feature = RecordingFeature(commander, "work", ["get initial"])
1701: +                following = RecordingFeature(commander, "following", ["get status"])
1702: +                commander.register_cleanup(feature, CleanupAction(
1703: +                    "close", CommandSequence("close", ["end"]),
1704: +                ))
1705: +                commander.start([feature, following])
1706: +                self.prompt(commander)
1707: +                self.prompt(commander)
1708: +                self.assertEqual(self.writes(terminal)[-1], "end\r")
1709: +                if best_effort:
1710: +                    self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
1711: +                    self.assertEqual(commander.feature_errors[0][0], "cleanup")
1712: +                    self.assertEqual(self.writes(terminal)[-1], "get status\r")
1713: +                else:
1714: +                    with self.assertRaisesRegex(RuntimeError, "return code -5"):
1715: +                        self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
1716: +                    self.assertNotIn("get status\r", self.writes(terminal))
1717: +
1718: +    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):
1719: +        terminal = MagicMock()
1720: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)
1721: +        feature = RecordingFeature(commander, "commit", [CommandSpec(
1722: +            "end", completion_states=(FOSCliState.CONFIRMATION,),
1723: +            expected_completion_state=FOSCliState.CMD_PROMPT,
1724: +        )])
1725: +        commander.start([feature])
1726: +        self.prompt(commander, "interface")
1727: +        with self.assertRaisesRegex(RuntimeError, "unexpected prompt"):
1728: +            commander.on_state(FOSCliState.CONFIRMATION, Data(b"Do you want to continue?"))
1729: +        self.assertEqual(self.writes(terminal), ["end\r"])
1730: +        self.assertFalse(feature.completed)
1731: +
1732: +
1733: +if __name__ == "__main__":
1734: +    unittest.main()
1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py
1736: index 1e31693..d633771 100644
1737: --- a/fortinet/tests/test_common_stack_boundaries.py
1738: +++ b/fortinet/tests/test_common_stack_boundaries.py
1739: @@ -38,15 +38,15 @@ class BoundaryFeature(Feature):
1740:  
1741:      def on_session_loss(self, attempt):
1742:          return SessionLossAction.CONTINUE
1743:  
1744:  
1745: -def make_stack(spec, response, *, allow_recovery=False):
1746: +def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b"fw #"):
1747:      logger = MagicMock()
1748:      connection = SerialConnection({
1749:          b"admin\r": b"Password:",
1750: -        b"secret\r": b"Welcome!\r\nfw #\r\n",
1751: +        b"secret\r": b"Welcome!\r\n" + initial_prompt + b"\r\n",
1752:          b"probe\r": response,
1753:      })
1754:      terminal = Terminal(connection, logger, default_wait="fw #")
1755:      commander = FOSCommander(terminal, logger)
1756:      feature = BoundaryFeature(commander, spec)
1757: @@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):
1758:      response = (
1759:          (prompt + " probe" + ending + "captured diagnostic" + ending + prompt + ending)
1760:          .encode()
1761:      )
1762:      spec = CommandSpec("probe", capture_output=True)
1763: -    connection, terminal, commander, driver, feature, states = make_stack(spec, response)
1764: +    connection, terminal, commander, driver, feature, states = make_stack(
1765: +        spec, response, initial_prompt=prompt.encode()
1766: +    )
1767:      try:
1768:          with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
1769:                  patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1770:              driver.process_state()
1771:          assert commander.ready
1772: @@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b"", *, recover=False):
1773:          completion = (state,)
1774:      connection, terminal, commander, driver, feature, states = make_stack(
1775:          CommandSpec("probe", completion_states=completion, capture_output=True),
1776:          response,
1777:          allow_recovery=recover,
1778: +        initial_prompt=b"fw (global) #" if state == FOSCliState.CMD_PROMPT_ECHO else b"fw #",
1779:      )
1780:      try:
1781:          with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.03), \
1782:                  patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1783:              driver.process_state()
1784: @@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):
1785:              self.assertFalse(feature.completed)
1786:              self.assertIn(b"garbage", bytes(feature.current_attempt.output))
1787:          finally:
1788:              terminal.close()
1789:  
1790: -    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):
1791: +    def test_idle_read_exposes_retained_prompt_newline(self):
1792:          connection, terminal, commander, driver, feature, states = make_stack(
1793:              CommandSpec("probe", capture_output=True), None
1794:          )
1795:          try:
1796:              with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
1797:                      patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.04):
1798:                  driver.process_state()
1799:              self.assertIn(FOSCliState.TN_TIMEOUT, states)
1800: -            self.assertEqual(bytes(feature.current_attempt.output), b"")
1801: +            # The login response ended with a newline after the matched CLI
1802: +            # prompt. Full-buffer timeout inspection exposes that real byte.
1803: +            self.assertEqual(bytes(feature.current_attempt.output), b"\n")
1804:              self.assertTrue(commander.busy)
1805:          finally:
1806:              terminal.close()
1807:  
1808:      def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):
1809:          command_echo = b"fw (global) # probe\r\n"
1810:          payload = b"config system dns\r\n set primary 1.1.1.1\r\nend\r\nfw (global) #\r\n"
1811:          response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])
1812:          connection, terminal, commander, driver, feature, states = make_stack(
1813: -            CommandSpec("probe", capture_output=True), response
1814: +            CommandSpec("probe", capture_output=True), response,
1815: +            initial_prompt=b"fw (global) #",
1816:          )
1817:          try:
1818:              with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
1819:                      patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1820:                  driver.process_state()
1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py
1822: index 74d6ef7..56346ea 100644
1823: --- a/fortinet/tests/test_common_stack_parsing.py
1824: +++ b/fortinet/tests/test_common_stack_parsing.py
1825: @@ -7,11 +7,13 @@ from pathlib import Path
1826:  from unittest.mock import MagicMock
1827:  
1828:  REPO_ROOT = Path(__file__).resolve().parents[2]
1829:  sys.path.insert(0, str(REPO_ROOT))
1830:  
1831: -from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402
1832: +from fortinet.common.cli_commands import (  # noqa: E402
1833: +    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,
1834: +)
1835:  from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
1836:  from fortinet.common.features.base import Feature  # noqa: E402
1837:  from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
1838:  from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1839:  from fortinet.common.terminal import Terminal  # noqa: E402
1840: @@ -35,10 +37,12 @@ class SerialConnection:
1841:  
1842:      def write(self, data):
1843:          data = bytes(data)
1844:          self.writes.append(data)
1845:          response = self._responses.get(data)
1846: +        if callable(response):
1847: +            response = response()
1848:          if response:
1849:              chunks = response if isinstance(response, (tuple, list)) else (response,)
1850:              for chunk in chunks:
1851:                  if chunk:
1852:                      self._incoming.put(bytes(chunk))
1853: @@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):
1854:          self.assertEqual(bytes(terminal._buffer), b"")
1855:  
1856:      def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):
1857:          responses = {
1858:              b"admin\r": b"Password:",
1859: -            b"secret\r": b"Welcome!\r\nfw #\r\n",
1860: +            b"secret\r": b"Welcome!\r\nfw (global) #\r\n",
1861:              b"get system status\r": (
1862:                  b"fw (global) # get system status\r\n"
1863:                  b"Version: FortiGate-VM64 v7.4.2,build2571\r\n"
1864:                  b"--More--\r\n"
1865:                  b"Serial-Number: FGVMTEST\r\n"
1866: @@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):
1867:          self.assertIn(b"FortiGate-VM64 v7.4.2,build2571", captured)
1868:          self.assertIn(b"Serial-Number: FGVMTEST", captured)
1869:          self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)
1870:          self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)
1871:  
1872: +    def test_aborted_interface_edit_recovers_through_serial_driver(self):
1873: +        ip_responses = iter([
1874: +            b"abort\r\nfw (Interim)#\r\n",
1875: +            b"fw (port1) (Interim)#\r\n",
1876: +        ])
1877: +        responses = {
1878: +            b"admin\r": b"Password:",
1879: +            b"secret\r": b"Welcome!\r\nfw (Interim)#\r\n",
1880: +            b"config system interface\r": b"fw (interface) (Interim)#\r\n",
1881: +            b"edit port1\r": b"fw (port1) (Interim)#\r\n",
1882: +            b"set ip 10.0.52.4/24\r": lambda: next(ip_responses),
1883: +            b"set allowaccess ping https ssh http\r": b"fw (port1) (Interim)#\r\n",
1884: +            b"next\r": b"fw (interface) (Interim)#\r\n",
1885: +            b"end\r": b"fw (Interim)#\r\n",
1886: +        }
1887: +        feature_ref = []
1888: +
1889: +        def configured(commander):
1890: +            feature = RecordingFeature(commander, "management", [
1891: +                ConfigBlock("system interface", [EditBlock("port1", [
1892: +                    "set ip 10.0.52.4/24", "set allowaccess ping https ssh http",
1893: +                ])]),
1894: +            ])
1895: +            feature_ref.append(feature)
1896: +            return [feature]
1897: +
1898: +        connection, terminal, commander, driver = self.make_stack(configured, responses)
1899: +        try:
1900: +            driver.process_state()
1901: +            self.assertTrue(commander.ready)
1902: +            self.assertTrue(feature_ref[0].completed)
1903: +            self.assertEqual(connection.writes, [
1904: +                b"admin\r", b"secret\r",
1905: +                b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
1906: +                b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
1907: +                b"set allowaccess ping https ssh http\r", b"next\r", b"end\r",
1908: +            ])
1909: +        finally:
1910: +            terminal.close()
1911: +
1912: +    def test_failed_next_ejects_before_end_through_serial_driver(self):
1913: +        responses = {
1914: +            b"admin\r": b"Password:",
1915: +            b"secret\r": b"Welcome!\r\nfw #\r\n",
1916: +            b"config system interface\r": b"fw (interface)#\r\n",
1917: +            b"edit port1\r": b"fw (port1)#\r\n",
1918: +            b"set unsupported 1\r": b"Command fail. Return code -61.\r\nfw (port1)#\r\n",
1919: +            b"next\r": (
1920: +                b"Command fa", b"il. Return code -5.\r\nfw (port1)#\r\n",
1921: +            ),
1922: +        }
1923: +        feature_ref = []
1924: +
1925: +        def configured(commander):
1926: +            feature = RecordingFeature(commander, "management", [
1927: +                ConfigBlock("system interface", [EditBlock("port1", ["set unsupported 1"])]),
1928: +            ])
1929: +            feature_ref.append(feature)
1930: +            return [feature]
1931: +
1932: +        connection, terminal, commander, driver = self.make_stack(configured, responses)
1933: +        try:
1934: +            with self.assertRaisesRegex(RuntimeError, "'next'.*return code -5"):
1935: +                driver.process_state()
1936: +            self.assertEqual(connection.writes, [
1937: +                b"admin\r", b"secret\r", b"config system interface\r",
1938: +                b"edit port1\r", b"set unsupported 1\r", b"next\r",
1939: +            ])
1940: +            self.assertFalse(feature_ref[0].completed)
1941: +            self.assertFalse(commander.ready)
1942: +        finally:
1943: +            terminal.close()
1944: +
1945:  
1946:  if __name__ == "__main__":
1947:      unittest.main()
1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py
1949: index 4c0a37b..be7eab4 100644
1950: --- a/fortinet/tests/test_common_terminal_driver.py
1951: +++ b/fortinet/tests/test_common_terminal_driver.py
1952: @@ -9,12 +9,16 @@ from contextlib import contextmanager
1953:  from unittest.mock import MagicMock, patch
1954:  
1955:  REPO_ROOT = __import__("pathlib").Path(__file__).resolve().parents[2]
1956:  sys.path.insert(0, str(REPO_ROOT))
1957:  
1958: -from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
1959: -from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
1960: +from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402
1961: +from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402
1962: +from fortinet.common.fos_cli_driver import (  # noqa: E402
1963: +    FOSCliDriver,
1964: +    KernelPanicError,
1965: +)
1966:  from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402
1967:  
1968:  
1969:  class ByteQueueTests(unittest.TestCase):
1970:      def test_put_get_close_timeout_and_failure(self):
1971: @@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):
1972:          terminal._buffer_limit = 5
1973:          with self.assertRaisesRegex(RuntimeError, "exceeded 5"):
1974:              terminal._enforce_buffer_limit()
1975:          terminal._logger.error.assert_called_once()
1976:  
1977: +    def test_timeout_preserves_partial_token_for_a_later_read(self):
1978: +        terminal = self.terminal_with_data(b"Login incor")
1979: +        pattern = rb"(?m)^Login incorrect\r?$"
1980: +        index, match, output = terminal.expect([pattern], timeout=0.001)
1981: +        self.assertEqual((index, match), (-1, None))
1982: +        self.assertEqual(bytes(output), b"Login incor")
1983: +        # Inspection without discard keeps the partial token, including when
1984: +        # another wait expires without receiving any more bytes.
1985: +        _, _, output = terminal.expect([pattern], timeout=0)
1986: +        self.assertEqual(bytes(output), b"Login incor")
1987: +        terminal._read_queue.put(b"rect\n")
1988: +        index, match, output = terminal.expect([pattern], timeout=0.1)
1989: +        self.assertEqual(index, 0)
1990: +        self.assertEqual(match.group(), b"Login incorrect")
1991: +        self.assertEqual(bytes(output), b"Login incorrect")
1992: +        self.assertEqual(bytes(terminal._buffer), b"\n")
1993: +
1994: +    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):
1995: +        terminal = self.terminal_with_data(b"Verifying pass")
1996: +        _, _, output = terminal.expect([b"fw #"], timeout=0.001)
1997: +        self.assertIsNone(re.search(rb"Verifying password", bytes(output)))
1998: +
1999: +        terminal._read_queue.put(b"word...\n")
2000: +        _, match, output = terminal.expect([b"fw #"], timeout=0.001)
2001: +        self.assertIsNone(match)
2002: +        self.assertIsNotNone(re.search(rb"Verifying password", bytes(output)))
2003: +        self.assertEqual(bytes(terminal._buffer), b"Verifying password...\n")
2004: +        output.discard()
2005: +        self.assertEqual(bytes(terminal._buffer), b"")
2006: +
2007: +    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):
2008: +        prefix = b"\nVerifying password...\n"
2009: +        chunk = b"admin\nadmin\n"
2010: +        terminal = self.terminal_with_data(chunk)
2011: +        terminal._buffer.extend(prefix)
2012: +
2013: +        _, _, output = terminal.expect([b"fw #"], timeout=0.001)
2014: +        self.assertEqual(bytes(output), prefix + chunk)
2015: +        attempt = CommandAttempt(CommandSpec("end"), 1, 0)
2016: +        attempt.on_output(output)
2017: +
2018: +        self.assertEqual(bytes(attempt.output), prefix + chunk)
2019: +        self.assertEqual(bytes(terminal._buffer), b"")
2020: +        terminal._logger.warning.assert_not_called()
2021: +
2022:      def test_suppression_is_nested_and_restores_context(self):
2023:          @contextmanager
2024:          def context():
2025:              events.append("enter")
2026:              try:
2027: @@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):
2028:          with self.assertRaisesRegex(OSError, "serial failed"):
2029:              queue.get(0)
2030:          logger.exception.assert_called_once()
2031:          with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}):
2032:              self.assertEqual(terminal_buffer_limit_bytes(), 32)
2033: -        with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "0"}):
2034: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "64", "FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}, clear=True):
2035: +            self.assertEqual(terminal_buffer_limit_bytes(), 64)
2036: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "0"}, clear=True):
2037:              with self.assertRaises(ValueError):
2038:                  terminal_buffer_limit_bytes()
2039:  
2040: +    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):
2041: +        for env_name in ("FTNT_LOG_RAW_SERIAL", "FOS_LOG_RAW_SERIAL"):
2042: +            with self.subTest(env_name=env_name):
2043: +                terminal = self.terminal_with_data(b"matched")
2044: +                with patch.dict("os.environ", {env_name: "true"}, clear=True):
2045: +                    terminal.expect([b"matched"], timeout=0.1)
2046: +                terminal._logger.log.assert_called_once_with(
2047: +                    TRACE_LEVEL,
2048: +                    "buffer: bytearray(b'matched')",
2049: +                )
2050: +
2051:  
2052:  class DriverTests(unittest.TestCase):
2053:      def make_driver(self, *, allow_recovery=False):
2054:          terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()
2055:          commander.ready = False
2056: @@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):
2057:          self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)
2058:          terminal.expect.return_value = (-1, None, Data(b""))
2059:          self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)
2060:          driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)
2061:  
2062: +    def test_retained_timeout_output_does_not_count_as_fresh_input(self):
2063: +        driver, _, _, logger, *_ = self.make_driver()
2064: +        terminal = Terminal(MagicMock(), logger)
2065: +        terminal._ensure_reader = lambda: None
2066: +        terminal._read_queue.put(b"partial token")
2067: +        driver._terminal = terminal
2068: +
2069: +        with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.001):
2070: +            state, output, matched = driver._next_state()
2071: +            self.assertEqual(state, FOSCliState.UNKNOWN)
2072: +            self.assertEqual(bytes(output), b"partial token")
2073: +            self.assertFalse(matched)
2074: +            state, output, matched = driver._next_state()
2075: +            self.assertEqual(state, FOSCliState.TN_TIMEOUT)
2076: +            self.assertEqual(bytes(output), b"partial token")
2077: +            self.assertFalse(matched)
2078: +
2079: +    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):
2080: +        driver, terminal, commander, *_ = self.make_driver()
2081: +        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]
2082: +        panic = (
2083: +            b"Kernel panic - not syncing: VFS: Unable to mount root fs\r\n"
2084: +            b"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\r\n"
2085: +        )
2086: +
2087: +        self.assertIsNone(
2088: +            re.search(
2089: +                pattern,
2090: +                b"Kernel panic - not syncing: VFS: Unable to mount root fs",
2091: +            )
2092: +        )
2093: +        match = re.search(pattern, panic)
2094: +        self.assertIsNotNone(match)
2095: +        terminal.expect.return_value = (
2096: +            FOSCliState.KERNEL_PANIC.value,
2097: +            match,
2098: +            Data(panic),
2099: +        )
2100: +
2101: +        with self.assertRaisesRegex(KernelPanicError, "Kernel panic detected"):
2102: +            driver.process_state()
2103: +
2104: +        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))
2105: +
2106:  
2107:  if __name__ == "__main__":
2108:      unittest.main()

(End of file - total 2108 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d12827001Rbj50rIAN5A3wy",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d11bcd001Vfv50xKiBoiGMh",
  "callID": "call_0d40192d024546af81dd7a78",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 1198,
      "limit": 1200
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1198: +        def activate_desired():\n1199: +            driver.remember_current_credentials()\n1200: +            credentials.username = username\n1201: +            credentials.password = password\n1202: +\n1203: +        vm = SimpleNamespace(\n1204: +            desired_credentials=Credentials(username, password),\n1205: +            activate_desired_credentials=activate_desired,\n1206: +        )\n1207: +        admin = CredentialsFeature(vm, commander)\n1208: +        following = RecordingFeature(commander, \"following\", [\"probe\"])\n1209: +        commander.start([admin, following])\n1210: +        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n1211: +        return connection, commander, driver, admin, following\n1212: +\n1213: +    def run_driver(self, driver):\n1214: +        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n1215: +                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n1216: +            driver.process_state()\n1217: +\n1218: +    def test_logout_and_relogin_after_committing_credentials(self):\n1219: +        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n1220: +                                   (\"operator\", \"newpass\")):\n1221: +            with self.subTest(username=username, password_set=bool(password)):\n1222: +                conn, cmd, driver, admin, following = self.make_stack(\n1223: +                    username=username, password=password,\n1224: +                )\n1225: +                self.run_driver(driver)\n1226: +                self.assertTrue(cmd.ready)\n1227: +                self.assertTrue(admin.completed)\n1228: +                self.assertTrue(following.completed)\n1229: +                logout = conn.writes.index(b\"exit\\r\")\n1230: +                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n1231: +                self.assertEqual(conn.writes[logout + 1:], [\n1232: +                    (username + \"\\r\").encode(),\n1233: +                    (password + \"\\r\").encode(),\n1234: +                    b\"probe\\r\",\n1235: +                ])\n1236: +                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n1237: +\n1238: +    def test_later_features_wait_for_authentication(self):\n1239: +        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n1240: +        self.run_driver(driver)\n1241: +        self.assertIn(b\"exit\\r\", conn.writes)\n1242: +        self.assertIn(b\"newpass\\r\", conn.writes)\n1243: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1244: +        self.assertFalse(admin.completed)\n1245: +        self.assertFalse(following.completed)\n1246: +        self.assertFalse(cmd.ready)\n1247: +\n1248: +    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n1249: +        for commit_command in (\"next\", \"end\"):\n1250: +            with self.subTest(commit_command=commit_command):\n1251: +                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n1252: +                self.run_driver(driver)\n1253: +                self.assertTrue(cmd.ready)\n1254: +                self.assertTrue(admin.completed)\n1255: +                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n1256: +                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n1257: +                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n1258: +\n1259: +    def test_logout_must_return_to_login(self):\n1260: +        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n1261: +        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n1262: +            self.run_driver(driver)\n1263: +        self.assertFalse(admin.completed)\n1264: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1265: +\n1266: +    def test_rejected_credentials_do_not_start_later_features(self):\n1267: +        conn, _, driver, admin, _ = self.make_stack(reject=True)\n1268: +        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n1269: +            self.run_driver(driver)\n1270: +        self.assertFalse(admin.completed)\n1271: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1272: +        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n1273: +\n1274: +\n1275: +if __name__ == \"__main__\":\n1276: +    unittest.main()\n1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\n1278: new file mode 100644\n1279: index 0000000..2afb43a\n1280: --- /dev/null\n1281: +++ b/fortinet/tests/test_common_recovery.py\n1282: @@ -0,0 +1,292 @@\n1283: +\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n1284: +\n1285: +import sys\n1286: +import unittest\n1287: +from pathlib import Path\n1288: +from unittest.mock import MagicMock\n1289: +\n1290: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1291: +\n1292: +from fortinet.common.cli_commands import (  # noqa: E402\n1293: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n1294: +    EditBlock, SessionLossAction,\n1295: +)\n1296: +from fortinet.common.common import FOSCliState  # noqa: E402\n1297: +from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n1298: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1299: +from fortinet.common.terminal import Data  # noqa: E402\n1300: +\n1301: +\n1302: +IP_COMMAND = \"set ip 10.0.52.4/24\"\n1303: +ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n1304: +\n1305: +\n1306: +class RecordingFeature(Feature):\n1307: +    def __init__(self, commander, block, context_action=None):\n1308: +        super().__init__(None, commander, \"management\")\n1309: +        self.block = block\n1310: +        self.context_action = context_action\n1311: +        self.losses = []\n1312: +        self.attempts = []\n1313: +        self.executed = []\n1314: +\n1315: +    def activate(self):\n1316: +        self.commander.submit_block(self, self.block)\n1317: +\n1318: +    def on_command_dispatched(self, attempt):\n1319: +        super().on_command_dispatched(attempt)\n1320: +        self.attempts.append(attempt)\n1321: +\n1322: +    def on_command_executed(self, attempt, state):\n1323: +        self.executed.append(attempt.spec.line)\n1324: +\n1325: +    def on_context_loss(self, attempt):\n1326: +        self.losses.append(attempt)\n1327: +        if self.context_action is not None:\n1328: +            return self.context_action\n1329: +        return super().on_context_loss(attempt)\n1330: +\n1331: +\n1332: +class RecoveryTests(unittest.TestCase):\n1333: +    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n1334: +                       context_action=None, following=False):\n1335: +        terminal = MagicMock()\n1336: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n1337: +        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1338: +            ip_command, ACCESS_COMMAND,\n1339: +        ])])\n1340: +        feature = RecordingFeature(commander, block, context_action)\n1341: +        features = [feature]\n1342: +        if following:\n1343: +            features.append(RecordingFeature(\n1344: +                commander, CommandSequence(\"following\", [\"get system status\"])\n1345: +            ))\n1346: +        commander.start(features)\n1347: +        return commander, terminal, feature\n1348: +\n1349: +    def prompt(self, commander, context=None):\n1350: +        scope = f\" ({context})\" if context else \"\"\n1351: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n1352: +            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n1353: +        ))\n1354: +\n1355: +    def enter_interface(self, commander):\n1356: +        self.prompt(commander, \"interface\")\n1357: +        self.prompt(commander, \"port1\")\n1358: +\n1359: +    def finish_interface(self, commander):\n1360: +        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n1361: +        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n1362: +        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n1363: +        self.prompt(commander)  # end succeeds.\n1364: +\n1365: +    @staticmethod\n1366: +    def writes(terminal):\n1367: +        return [call.args[0] for call in terminal.write.call_args_list]\n1368: +\n1369: +    def reconnect(self, commander):\n1370: +        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n1371: +        self.prompt(commander)\n1372: +\n1373: +    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n1374: +        commander, terminal, feature = self.make_commander()\n1375: +        self.prompt(commander)\n1376: +        self.enter_interface(commander)\n1377: +        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n1378: +        self.assertEqual(self.writes(terminal), [\n1379: +            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n1380: +            \"config system interface\\r\",\n1381: +        ])\n1382: +        self.assertNotIn(IP_COMMAND, feature.executed)\n1383: +        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n1384: +        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n1385: +        self.enter_interface(commander)\n1386: +        self.finish_interface(commander)\n1387: +        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n1388: +        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n1389: +        self.assertTrue(feature.completed)\n1390: +        self.assertTrue(commander.ready)\n1391: +\n1392: +    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n1393: +        for best_effort in (False, True):\n1394: +            with self.subTest(best_effort=best_effort):\n1395: +                commander, terminal, feature = self.make_commander(\n1396: +                    continue_on_error=best_effort, following=True,\n1397: +                )\n1398: +                self.prompt(commander)\n1399: +                self.enter_interface(commander)\n1400: +                self.prompt(commander)\n1401: +                self.enter_interface(commander)\n1402: +                if best_effort:\n1403: +                    self.prompt(commander)\n1404: +                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1405: +                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1406: +                else:\n1407: +                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1408: +                        self.prompt(commander)\n1409: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n1410: +                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n1411: +                self.assertFalse(feature.completed)\n1412: +\n1413: +    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n1414: +        commander, terminal, feature = self.make_commander()\n1415: +        self.prompt(commander)\n1416: +        self.enter_interface(commander)\n1417: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1418: +        self.reconnect(commander)\n1419: +        self.enter_interface(commander)\n1420: +        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1421: +            self.prompt(commander)\n1422: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n1423: +        self.assertEqual(feature.losses[0].retry_count, 1)\n1424: +\n1425: +    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n1426: +        commander, terminal, _feature = self.make_commander(\n1427: +            continue_on_error=True, following=True,\n1428: +        )\n1429: +        self.prompt(commander)\n1430: +        self.enter_interface(commander)\n1431: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1432: +        self.reconnect(commander)\n1433: +        self.enter_interface(commander)\n1434: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n1435: +        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n1436: +        self.reconnect(commander)\n1437: +        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1438: +        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1439: +\n1440: +    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n1441: +        commander, terminal, _feature = self.make_commander(\n1442: +            continue_on_error=True, following=True,\n1443: +        )\n1444: +        self.prompt(commander)\n1445: +        self.enter_interface(commander)\n1446: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1447: +        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n1448: +        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n1449: +        self.enter_interface(commander)\n1450: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n1451: +        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n1452: +        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n1453: +        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1454: +        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1455: +\n1456: +    def test_each_command_position_gets_one_recovery(self):\n1457: +        commander, terminal, feature = self.make_commander()\n1458: +        self.prompt(commander)\n1459: +        self.enter_interface(commander)\n1460: +        self.prompt(commander)  # First loss: IP command.\n1461: +        self.enter_interface(commander)\n1462: +        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n1463: +        self.prompt(commander)  # Second loss: allowaccess command.\n1464: +        self.enter_interface(commander)\n1465: +        self.finish_interface(commander)\n1466: +        self.assertTrue(feature.completed)\n1467: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n1468: +        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n1469: +\n1470: +    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n1471: +        for explicit_policy in (False, True):\n1472: +            with self.subTest(explicit_policy=explicit_policy):\n1473: +                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n1474: +                commander, terminal, feature = self.make_commander(\n1475: +                    ip_command=IP_COMMAND if explicit_policy else spec,\n1476: +                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n1477: +                )\n1478: +                feature.on_session_loss = MagicMock()\n1479: +                self.prompt(commander)\n1480: +                self.enter_interface(commander)\n1481: +                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n1482: +                    self.prompt(commander)\n1483: +                feature.on_session_loss.assert_not_called()\n1484: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n1485: +\n1486: +    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n1487: +        spec = CommandSpec(\n1488: +            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n1489: +            context_loss=ContextLossAction.RESTART_BLOCK,\n1490: +        )\n1491: +        commander, _terminal, feature = self.make_commander(ip_command=spec)\n1492: +        feature.on_session_loss = MagicMock()\n1493: +        self.prompt(commander)\n1494: +        self.enter_interface(commander)\n1495: +        self.prompt(commander)\n1496: +        self.enter_interface(commander)\n1497: +        self.finish_interface(commander)\n1498: +        self.assertTrue(feature.completed)\n1499: +        feature.on_session_loss.assert_not_called()\n1500: +\n1501: +    def test_partial_scope_is_aborted_once_before_replay(self):\n1502: +        commander, terminal, feature = self.make_commander()\n1503: +        self.prompt(commander)\n1504: +        self.enter_interface(commander)\n1505: +        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n1506: +        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n1507: +        self.prompt(commander)\n1508: +        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n1509: +        self.enter_interface(commander)\n1510: +        self.finish_interface(commander)\n1511: +        self.assertTrue(feature.completed)\n1512: +        self.assertNotIn(\"abort\", feature.executed)\n1513: +        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n1514: +\n1515: +    def test_failed_context_reset_does_not_loop(self):\n1516: +        commander, terminal, _feature = self.make_commander()\n1517: +        self.prompt(commander)\n1518: +        self.enter_interface(commander)\n1519: +        self.prompt(commander, \"interface\")\n1520: +        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n1521: +            self.prompt(commander, \"interface\")\n1522: +        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n1523: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n1524: +\n1525: +    def test_session_loss_during_context_reset_resumes_after_login(self):\n1526: +        commander, terminal, feature = self.make_commander()\n1527: +        self.prompt(commander)\n1528: +        self.enter_interface(commander)\n1529: +        self.prompt(commander, \"interface\")\n1530: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1531: +        self.reconnect(commander)\n1532: +        self.enter_interface(commander)\n1533: +        self.finish_interface(commander)\n1534: +        self.assertTrue(feature.completed)\n1535: +        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n1536: +\n1537: +    def test_cleanup_session_loss_is_bounded(self):\n1538: +        terminal = MagicMock()\n1539: +        commander = FOSCommander(terminal, MagicMock())\n1540: +        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n1541: +        commander.register_cleanup(feature, CleanupAction(\n1542: +            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n1543: +        ))\n1544: +        commander.start([feature])\n1545: +        self.prompt(commander)\n1546: +        self.prompt(commander)  # Begin cleanup after the feature completes.\n1547: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1548: +        self.reconnect(commander)\n1549: +        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1550: +            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1551: +        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n1552: +\n1553: +    def test_newly_submitted_block_resets_retry_allowance(self):\n1554: +        terminal = MagicMock()\n1555: +        commander = FOSCommander(terminal, MagicMock())\n1556: +        feature = StaticFeature(None, commander, \"two-blocks\", [\n1557: +            ConfigBlock(\"system global\", [\"set alias first\"]),\n1558: +            ConfigBlock(\"system global\", [\"set alias second\"]),\n1559: +        ])\n1560: +        commander.start([feature])\n1561: +        self.prompt(commander)\n1562: +        for _index in range(2):\n1563: +            self.prompt(commander, \"global\")\n1564: +            self.prompt(commander)  # Lost context: retry this block.\n1565: +            self.prompt(commander, \"global\")\n1566: +            self.prompt(commander, \"global\")\n1567: +            self.prompt(commander)  # End this block and start the next one.\n1568: +        self.assertTrue(feature.completed)\n1569: +        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n1570: +        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n1571: +\n1572: +\n1573: +if __name__ == \"__main__\":\n1574: +    unittest.main()\n1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\n1576: new file mode 100644\n1577: index 0000000..56ce729\n1578: --- /dev/null\n1579: +++ b/fortinet/tests/test_common_scope_errors.py\n1580: @@ -0,0 +1,154 @@\n1581: +\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n1582: +\n1583: +import sys\n1584: +import unittest\n1585: +from pathlib import Path\n1586: +from unittest.mock import MagicMock\n1587: +\n1588: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1589: +\n1590: +from fortinet.common.cli_commands import (  # noqa: E402\n1591: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n1592: +)\n1593: +from fortinet.common.common import FOSCliState  # noqa: E402\n1594: +from fortinet.common.features.base import Feature  # noqa: E402\n1595: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1596: +from fortinet.common.terminal import Data  # noqa: E402\n1597: +\n1598: +\n1599: +class RecordingFeature(Feature):\n1600: +    def __init__(self, commander, name, commands):\n1601: +        super().__init__(None, commander, name)\n1602: +        self.commands = commands\n1603: +        self.executed = []\n1604: +\n1605: +    def activate(self):\n1606: +        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n1607: +\n1608: +    def on_command_executed(self, attempt, state):\n1609: +        self.executed.append(attempt.spec.line)\n1610: +\n1611: +\n1612: +class ScopeCommitFailureTests(unittest.TestCase):\n1613: +    @staticmethod\n1614: +    def prompt(commander, context=None, output=b\"\"):\n1615: +        scope = f\" ({context})\" if context else \"\"\n1616: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n1617: +            output + f\"fw{scope} #\".encode()\n1618: +        ))\n1619: +\n1620: +    @staticmethod\n1621: +    def writes(terminal):\n1622: +        return [call.args[0] for call in terminal.write.call_args_list]\n1623: +\n1624: +    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n1625: +        for close in (\"next\", \"end\"):\n1626: +            for capture in (False, True):\n1627: +                for best_effort in (False, True):\n1628: +                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n1629: +                        terminal = MagicMock()\n1630: +                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n1631: +                        feature = RecordingFeature(commander, \"commit\", [\n1632: +                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n1633: +                            \"set must-not-run 1\",\n1634: +                        ])\n1635: +                        feature.on_context_loss = MagicMock()\n1636: +                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n1637: +                        commander.start([feature, following])\n1638: +                        self.prompt(commander, \"port1\")\n1639: +                        # The failure code can span multiple serial reads.\n1640: +                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n1641: +                            data = Data(chunk)\n1642: +                            commander.on_output(data)\n1643: +                            self.assertTrue(data.discarded)\n1644: +                        if best_effort:\n1645: +                            self.prompt(commander, \"interface\")\n1646: +                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n1647: +                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n1648: +                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n1649: +                        else:\n1650: +                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n1651: +                                self.prompt(commander, \"interface\")\n1652: +                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n1653: +                        feature.on_context_loss.assert_not_called()\n1654: +                        self.assertEqual(feature.executed, [])\n1655: +                        self.assertFalse(feature.completed)\n1656: +\n1657: +    def test_closing_failure_with_same_prompt_still_ejects(self):\n1658: +        for code in (\"0\", \"7\", \"-61\"):\n1659: +            for suffix in (\"\", \".\"):\n1660: +                with self.subTest(code=code, suffix=suffix):\n1661: +                    terminal = MagicMock()\n1662: +                    commander = FOSCommander(terminal, MagicMock())\n1663: +                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n1664: +                    commander.start([feature])\n1665: +                    self.prompt(commander, \"port1\")\n1666: +                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n1667: +                        self.prompt(\n1668: +                            commander, \"port1\",\n1669: +                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n1670: +                        )\n1671: +                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n1672: +\n1673: +    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n1674: +        for capture in (False, True):\n1675: +            with self.subTest(capture=capture):\n1676: +                terminal = MagicMock()\n1677: +                commander = FOSCommander(terminal, MagicMock())\n1678: +                feature = RecordingFeature(commander, \"configure\", [\n1679: +                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1680: +                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n1681: +                    ])]),\n1682: +                ])\n1683: +                commander.start([feature])\n1684: +                self.prompt(commander)\n1685: +                self.prompt(commander, \"interface\")\n1686: +                self.prompt(commander, \"port1\")\n1687: +                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n1688: +                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n1689: +                self.prompt(commander, \"interface\")\n1690: +                self.prompt(commander)\n1691: +                self.assertTrue(feature.completed)\n1692: +                self.assertTrue(commander.ready)\n1693: +                self.assertEqual(commander.feature_errors, ())\n1694: +\n1695: +    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n1696: +        for best_effort in (False, True):\n1697: +            with self.subTest(best_effort=best_effort):\n1698: +                terminal = MagicMock()\n1699: +                commander = FOSCommander(terminal, MagicMock(), best_effort)\n1700: +                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n1701: +                following = RecordingFeature(commander, \"following\", [\"get status\"])\n1702: +                commander.register_cleanup(feature, CleanupAction(\n1703: +                    \"close\", CommandSequence(\"close\", [\"end\"]),\n1704: +                ))\n1705: +                commander.start([feature, following])\n1706: +                self.prompt(commander)\n1707: +                self.prompt(commander)\n1708: +                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n1709: +                if best_effort:\n1710: +                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n1711: +                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n1712: +                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n1713: +                else:\n1714: +                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n1715: +                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n1716: +                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n1717: +\n1718: +    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n1719: +        terminal = MagicMock()\n1720: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n1721: +        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n1722: +            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n1723: +            expected_completion_state=FOSCliState.CMD_PROMPT,\n1724: +        )])\n1725: +        commander.start([feature])\n1726: +        self.prompt(commander, \"interface\")\n1727: +        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n1728: +            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n1729: +        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n1730: +        self.assertFalse(feature.completed)\n1731: +\n1732: +\n1733: +if __name__ == \"__main__\":\n1734: +    unittest.main()\n1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\n1736: index 1e31693..d633771 100644\n1737: --- a/fortinet/tests/test_common_stack_boundaries.py\n1738: +++ b/fortinet/tests/test_common_stack_boundaries.py\n1739: @@ -38,15 +38,15 @@ class BoundaryFeature(Feature):\n1740:  \n1741:      def on_session_loss(self, attempt):\n1742:          return SessionLossAction.CONTINUE\n1743:  \n1744:  \n1745: -def make_stack(spec, response, *, allow_recovery=False):\n1746: +def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n1747:      logger = MagicMock()\n1748:      connection = SerialConnection({\n1749:          b\"admin\\r\": b\"Password:\",\n1750: -        b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1751: +        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n1752:          b\"probe\\r\": response,\n1753:      })\n1754:      terminal = Terminal(connection, logger, default_wait=\"fw #\")\n1755:      commander = FOSCommander(terminal, logger)\n1756:      feature = BoundaryFeature(commander, spec)\n1757: @@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):\n1758:      response = (\n1759:          (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n1760:          .encode()\n1761:      )\n1762:      spec = CommandSpec(\"probe\", capture_output=True)\n1763: -    connection, terminal, commander, driver, feature, states = make_stack(spec, response)\n1764: +    connection, terminal, commander, driver, feature, states = make_stack(\n1765: +        spec, response, initial_prompt=prompt.encode()\n1766: +    )\n1767:      try:\n1768:          with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n1769:                  patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1770:              driver.process_state()\n1771:          assert commander.ready\n1772: @@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b\"\", *, recover=False):\n1773:          completion = (state,)\n1774:      connection, terminal, commander, driver, feature, states = make_stack(\n1775:          CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n1776:          response,\n1777:          allow_recovery=recover,\n1778: +        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n1779:      )\n1780:      try:\n1781:          with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n1782:                  patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1783:              driver.process_state()\n1784: @@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):\n1785:              self.assertFalse(feature.completed)\n1786:              self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n1787:          finally:\n1788:              terminal.close()\n1789:  \n1790: -    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):\n1791: +    def test_idle_read_exposes_retained_prompt_newline(self):\n1792:          connection, terminal, commander, driver, feature, states = make_stack(\n1793:              CommandSpec(\"probe\", capture_output=True), None\n1794:          )\n1795:          try:\n1796:              with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n1797:                      patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n1798:                  driver.process_state()\n1799:              self.assertIn(FOSCliState.TN_TIMEOUT, states)\n1800: -            self.assertEqual(bytes(feature.current_attempt.output), b\"\")\n1801: +            # The login response ended with a newline after the matched CLI\n1802: +            # prompt. Full-buffer timeout inspection exposes that real byte.\n1803: +            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n1804:              self.assertTrue(commander.busy)\n1805:          finally:\n1806:              terminal.close()\n1807:  \n1808:      def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n1809:          command_echo = b\"fw (global) # probe\\r\\n\"\n1810:          payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n1811:          response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n1812:          connection, terminal, commander, driver, feature, states = make_stack(\n1813: -            CommandSpec(\"probe\", capture_output=True), response\n1814: +            CommandSpec(\"probe\", capture_output=True), response,\n1815: +            initial_prompt=b\"fw (global) #\",\n1816:          )\n1817:          try:\n1818:              with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n1819:                      patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1820:                  driver.process_state()\n1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\n1822: index 74d6ef7..56346ea 100644\n1823: --- a/fortinet/tests/test_common_stack_parsing.py\n1824: +++ b/fortinet/tests/test_common_stack_parsing.py\n1825: @@ -7,11 +7,13 @@ from pathlib import Path\n1826:  from unittest.mock import MagicMock\n1827:  \n1828:  REPO_ROOT = Path(__file__).resolve().parents[2]\n1829:  sys.path.insert(0, str(REPO_ROOT))\n1830:  \n1831: -from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402\n1832: +from fortinet.common.cli_commands import (  # noqa: E402\n1833: +    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n1834: +)\n1835:  from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n1836:  from fortinet.common.features.base import Feature  # noqa: E402\n1837:  from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n1838:  from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1839:  from fortinet.common.terminal import Terminal  # noqa: E402\n1840: @@ -35,10 +37,12 @@ class SerialConnection:\n1841:  \n1842:      def write(self, data):\n1843:          data = bytes(data)\n1844:          self.writes.append(data)\n1845:          response = self._responses.get(data)\n1846: +        if callable(response):\n1847: +            response = response()\n1848:          if response:\n1849:              chunks = response if isinstance(response, (tuple, list)) else (response,)\n1850:              for chunk in chunks:\n1851:                  if chunk:\n1852:                      self._incoming.put(bytes(chunk))\n1853: @@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):\n1854:          self.assertEqual(bytes(terminal._buffer), b\"\")\n1855:  \n1856:      def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n1857:          responses = {\n1858:              b\"admin\\r\": b\"Password:\",\n1859: -            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1860: +            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n1861:              b\"get system status\\r\": (\n1862:                  b\"fw (global) # get system status\\r\\n\"\n1863:                  b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n1864:                  b\"--More--\\r\\n\"\n1865:                  b\"Serial-Number: FGVMTEST\\r\\n\"\n1866: @@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):\n1867:          self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n1868:          self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n1869:          self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n1870:          self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n1871:  \n1872: +    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n1873: +        ip_responses = iter([\n1874: +            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n1875: +            b\"fw (port1) (Interim)#\\r\\n\",\n1876: +        ])\n1877: +        responses = {\n1878: +            b\"admin\\r\": b\"Password:\",\n1879: +            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n1880: +            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n1881: +            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n1882: +            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n1883: +            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n1884: +            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n1885: +            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n1886: +        }\n1887: +        feature_ref = []\n1888: +\n1889: +        def configured(commander):\n1890: +            feature = RecordingFeature(commander, \"management\", [\n1891: +                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1892: +                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n1893: +                ])]),\n1894: +            ])\n1895: +            feature_ref.append(feature)\n1896: +            return [feature]\n1897: +\n1898: +        connection, terminal, commander, driver = self.make_stack(configured, responses)\n1899: +        try:\n1900: +            driver.process_state()\n1901: +            self.assertTrue(commander.ready)\n1902: +            self.assertTrue(feature_ref[0].completed)\n1903: +            self.assertEqual(connection.writes, [\n1904: +                b\"admin\\r\", b\"secret\\r\",\n1905: +                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n1906: +                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n1907: +                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n1908: +            ])\n1909: +        finally:\n1910: +            terminal.close()\n1911: +\n1912: +    def test_failed_next_ejects_before_end_through_serial_driver(self):\n1913: +        responses = {\n1914: +            b\"admin\\r\": b\"Password:\",\n1915: +            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1916: +            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n1917: +            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n1918: +            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n1919: +            b\"next\\r\": (\n1920: +                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n1921: +            ),\n1922: +        }\n1923: +        feature_ref = []\n1924: +\n1925: +        def configured(commander):\n1926: +            feature = RecordingFeature(commander, \"management\", [\n1927: +                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n1928: +            ])\n1929: +            feature_ref.append(feature)\n1930: +            return [feature]\n1931: +\n1932: +        connection, terminal, commander, driver = self.make_stack(configured, responses)\n1933: +        try:\n1934: +            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n1935: +                driver.process_state()\n1936: +            self.assertEqual(connection.writes, [\n1937: +                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n1938: +                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n1939: +            ])\n1940: +            self.assertFalse(feature_ref[0].completed)\n1941: +            self.assertFalse(commander.ready)\n1942: +        finally:\n1943: +            terminal.close()\n1944: +\n1945:  \n1946:  if __name__ == \"__main__\":\n1947:      unittest.main()\n1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\n1949: index 4c0a37b..be7eab4 100644\n1950: --- a/fortinet/tests/test_common_terminal_driver.py\n1951: +++ b/fortinet/tests/test_common_terminal_driver.py\n1952: @@ -9,12 +9,16 @@ from contextlib import contextmanager\n1953:  from unittest.mock import MagicMock, patch\n1954:  \n1955:  REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n1956:  sys.path.insert(0, str(REPO_ROOT))\n1957:  \n1958: -from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n1959: -from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n1960: +from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n1961: +from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n1962: +from fortinet.common.fos_cli_driver import (  # noqa: E402\n1963: +    FOSCliDriver,\n1964: +    KernelPanicError,\n1965: +)\n1966:  from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n1967:  \n1968:  \n1969:  class ByteQueueTests(unittest.TestCase):\n1970:      def test_put_get_close_timeout_and_failure(self):\n1971: @@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):\n1972:          terminal._buffer_limit = 5\n1973:          with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n1974:              terminal._enforce_buffer_limit()\n1975:          terminal._logger.error.assert_called_once()\n1976:  \n1977: +    def test_timeout_preserves_partial_token_for_a_later_read(self):\n1978: +        terminal = self.terminal_with_data(b\"Login incor\")\n1979: +        pattern = rb\"(?m)^Login incorrect\\r?$\"\n1980: +        index, match, output = terminal.expect([pattern], timeout=0.001)\n1981: +        self.assertEqual((index, match), (-1, None))\n1982: +        self.assertEqual(bytes(output), b\"Login incor\")\n1983: +        # Inspection without discard keeps the partial token, including when\n1984: +        # another wait expires without receiving any more bytes.\n1985: +        _, _, output = terminal.expect([pattern], timeout=0)\n1986: +        self.assertEqual(bytes(output), b\"Login incor\")\n1987: +        terminal._read_queue.put(b\"rect\\n\")\n1988: +        index, match, output = terminal.expect([pattern], timeout=0.1)\n1989: +        self.assertEqual(index, 0)\n1990: +        self.assertEqual(match.group(), b\"Login incorrect\")\n1991: +        self.assertEqual(bytes(output), b\"Login incorrect\")\n1992: +        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n1993: +\n1994: +    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n1995: +        terminal = self.terminal_with_data(b\"Verifying pass\")\n1996: +        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n1997: +        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n1998: +\n1999: +        terminal._read_queue.put(b\"word...\\n\")\n2000: +        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n2001: +        self.assertIsNone(match)\n2002: +        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n2003: +        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n2004: +        output.discard()\n2005: +        self.assertEqual(bytes(terminal._buffer), b\"\")\n2006: +\n2007: +    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n2008: +        prefix = b\"\\nVerifying password...\\n\"\n2009: +        chunk = b\"admin\\nadmin\\n\"\n2010: +        terminal = self.terminal_with_data(chunk)\n2011: +        terminal._buffer.extend(prefix)\n2012: +\n2013: +        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n2014: +        self.assertEqual(bytes(output), prefix + chunk)\n2015: +        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n2016: +        attempt.on_output(output)\n2017: +\n2018: +        self.assertEqual(bytes(attempt.output), prefix + chunk)\n2019: +        self.assertEqual(bytes(terminal._buffer), b\"\")\n2020: +        terminal._logger.warning.assert_not_called()\n2021: +\n2022:      def test_suppression_is_nested_and_restores_context(self):\n2023:          @contextmanager\n2024:          def context():\n2025:              events.append(\"enter\")\n2026:              try:\n2027: @@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):\n2028:          with self.assertRaisesRegex(OSError, \"serial failed\"):\n2029:              queue.get(0)\n2030:          logger.exception.assert_called_once()\n2031:          with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n2032:              self.assertEqual(terminal_buffer_limit_bytes(), 32)\n2033: -        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n2034: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n2035: +            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n2036: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n2037:              with self.assertRaises(ValueError):\n2038:                  terminal_buffer_limit_bytes()\n2039:  \n2040: +    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n2041: +        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n2042: +            with self.subTest(env_name=env_name):\n2043: +                terminal = self.terminal_with_data(b\"matched\")\n2044: +                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n2045: +                    terminal.expect([b\"matched\"], timeout=0.1)\n2046: +                terminal._logger.log.assert_called_once_with(\n2047: +                    TRACE_LEVEL,\n2048: +                    \"buffer: bytearray(b'matched')\",\n2049: +                )\n2050: +\n2051:  \n2052:  class DriverTests(unittest.TestCase):\n2053:      def make_driver(self, *, allow_recovery=False):\n2054:          terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n2055:          commander.ready = False\n2056: @@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):\n2057:          self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n2058:          terminal.expect.return_value = (-1, None, Data(b\"\"))\n2059:          self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n2060:          driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n2061:  \n2062: +    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n2063: +        driver, _, _, logger, *_ = self.make_driver()\n2064: +        terminal = Terminal(MagicMock(), logger)\n2065: +        terminal._ensure_reader = lambda: None\n2066: +        terminal._read_queue.put(b\"partial token\")\n2067: +        driver._terminal = terminal\n2068: +\n2069: +        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n2070: +            state, output, matched = driver._next_state()\n2071: +            self.assertEqual(state, FOSCliState.UNKNOWN)\n2072: +            self.assertEqual(bytes(output), b\"partial token\")\n2073: +            self.assertFalse(matched)\n2074: +            state, output, matched = driver._next_state()\n2075: +            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n2076: +            self.assertEqual(bytes(output), b\"partial token\")\n2077: +            self.assertFalse(matched)\n2078: +\n2079: +    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n2080: +        driver, terminal, commander, *_ = self.make_driver()\n2081: +        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n2082: +        panic = (\n2083: +            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n2084: +            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n2085: +        )\n2086: +\n2087: +        self.assertIsNone(\n2088: +            re.search(\n2089: +                pattern,\n2090: +                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n2091: +            )\n2092: +        )\n2093: +        match = re.search(pattern, panic)\n2094: +        self.assertIsNotNone(match)\n2095: +        terminal.expect.return_value = (\n2096: +            FOSCliState.KERNEL_PANIC.value,\n2097: +            match,\n2098: +            Data(panic),\n2099: +        )\n2100: +\n2101: +        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n2102: +            driver.process_state()\n2103: +\n2104: +        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n2105: +\n2106:  \n2107:  if __name__ == \"__main__\":\n2108:      unittest.main()\n\n(End of file - total 2108 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+        def activate_desired():\n+            driver.remember_current_credentials()\n+            credentials.username = username\n+            credentials.password = password\n+\n+        vm = SimpleNamespace(\n+            desired_credentials=Credentials(username, password),\n+            activate_desired_credentials=activate_desired,\n+        )\n+        admin = CredentialsFeature(vm, commander)\n+        following = RecordingFeature(commander, \"following\", [\"probe\"])\n+        commander.start([admin, following])\n+        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n+        return connection, commander, driver, admin, following\n+\n+    def run_driver(self, driver):\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n+                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n+            driver.process_state()\n+",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+        def activate_desired():\n+            driver.remember_current_credentials()\n+            credentials.username = username\n+            credentials.password = password\n+\n+        vm = SimpleNamespace(\n+            desired_credentials=Credentials(username, password),\n+            activate_desired_credentials=activate_desired,\n+        )\n+        admin = CredentialsFeature(vm, commander)\n+        following = RecordingFeature(commander, \"following\", [\"probe\"])\n+        commander.start([admin, following])\n+        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n+        return connection, commander, driver, admin, following\n+\n+    def run_driver(self, driver):\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n+                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n+            driver.process_state()\n+\n+    def test_logout_and_relogin_after_committing_credentials(self):\n+        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n+                                   (\"operator\", \"newpass\")):\n+            with self.subTest(username=username, password_set=bool(password)):\n+                conn, cmd, driver, admin, following = self.make_stack(\n+                    username=username, password=password,\n+                )\n+                self.run_driver(driver)\n+                self.assertTrue(cmd.ready)\n+                self.assertTrue(admin.completed)\n+                self.assertTrue(following.completed)\n+                logout = conn.writes.index(b\"exit\\r\")\n+                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n+                self.assertEqual(conn.writes[logout + 1:], [\n+                    (username + \"\\r\").encode(),\n+                    (password + \"\\r\").encode(),\n+                    b\"probe\\r\",\n+                ])\n+                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n+\n+    def test_later_features_wait_for_authentication(self):\n+        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n+        self.run_driver(driver)\n+        self.assertIn(b\"exit\\r\", conn.writes)\n+        self.assertIn(b\"newpass\\r\", conn.writes)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+        self.assertFalse(admin.completed)\n+        self.assertFalse(following.completed)\n+        self.assertFalse(cmd.ready)\n+\n+    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n+        for commit_command in (\"next\", \"end\"):\n+            with self.subTest(commit_command=commit_command):\n+                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n+                self.run_driver(driver)\n+                self.assertTrue(cmd.ready)\n+                self.assertTrue(admin.completed)\n+                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n+                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n+                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n+\n+    def test_logout_must_return_to_login(self):\n+        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n+        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n+            self.run_driver(driver)\n+        self.assertFalse(admin.completed)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+\n+    def test_rejected_credentials_do_not_start_later_features(self):\n+        conn, _, driver, admin, _ = self.make_stack(reject=True)\n+        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n+            self.run_driver(driver)\n+        self.assertFalse(admin.completed)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\nnew file mode 100644\nindex 0000000..2afb43a\n--- /dev/null\n+++ b/fortinet/tests/test_common_recovery.py\n@@ -0,0 +1,292 @@\n+\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n+    EditBlock, SessionLossAction,\n+)\n+from fortinet.common.common import FOSCliState  # noqa: E402\n+from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n+from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n+from fortinet.common.terminal import Data  # noqa: E402\n+\n+\n+IP_COMMAND = \"set ip 10.0.52.4/24\"\n+ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n+\n+\n+class RecordingFeature(Feature):\n+    def __init__(self, commander, block, context_action=None):\n+        super().__init__(None, commander, \"management\")\n+        self.block = block\n+        self.context_action = context_action\n+        self.losses = []\n+        self.attempts = []\n+        self.executed = []\n+\n+    def activate(self):\n+        self.commander.submit_block(self, self.block)\n+\n+    def on_command_dispatched(self, attempt):\n+        super().on_command_dispatched(attempt)\n+        self.attempts.append(attempt)\n+\n+    def on_command_executed(self, attempt, state):\n+        self.executed.append(attempt.spec.line)\n+\n+    def on_context_loss(self, attempt):\n+        self.losses.append(attempt)\n+        if self.context_action is not None:\n+            return self.context_action\n+        return super().on_context_loss(attempt)\n+\n+\n+class RecoveryTests(unittest.TestCase):\n+    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n+                       context_action=None, following=False):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n+        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+            ip_command, ACCESS_COMMAND,\n+        ])])\n+        feature = RecordingFeature(commander, block, context_action)\n+        features = [feature]\n+        if following:\n+            features.append(RecordingFeature(\n+                commander, CommandSequence(\"following\", [\"get system status\"])\n+            ))\n+        commander.start(features)\n+        return commander, terminal, feature\n+\n+    def prompt(self, commander, context=None):\n+        scope = f\" ({context})\" if context else \"\"\n+        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n+            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n+        ))\n+\n+    def enter_interface(self, commander):\n+        self.prompt(commander, \"interface\")\n+        self.prompt(commander, \"port1\")\n+\n+    def finish_interface(self, commander):\n+        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n+        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n+        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n+        self.prompt(commander)  # end succeeds.\n+\n+    @staticmethod\n+    def writes(terminal):\n+        return [call.args[0] for call in terminal.write.call_args_list]\n+\n+    def reconnect(self, commander):\n+        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n+        self.prompt(commander)\n+\n+    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n+        self.assertEqual(self.writes(terminal), [\n+            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n+            \"config system interface\\r\",\n+        ])\n+        self.assertNotIn(IP_COMMAND, feature.executed)\n+        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n+        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n+        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n+        self.assertTrue(feature.completed)\n+        self.assertTrue(commander.ready)\n+\n+    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n+        for best_effort in (False, True):\n+            with self.subTest(best_effort=best_effort):\n+                commander, terminal, feature = self.make_commander(\n+                    continue_on_error=best_effort, following=True,\n+                )\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                if best_effort:\n+                    self.prompt(commander)\n+                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+                else:\n+                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+                        self.prompt(commander)\n+                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n+                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n+                self.assertFalse(feature.completed)\n+\n+    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+            self.prompt(commander)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n+        self.assertEqual(feature.losses[0].retry_count, 1)\n+\n+    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n+        commander, terminal, _feature = self.make_commander(\n+            continue_on_error=True, following=True,\n+        )\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n+        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n+        self.reconnect(commander)\n+        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+\n+    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n+        commander, terminal, _feature = self.make_commander(\n+            continue_on_error=True, following=True,\n+        )\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n+        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n+        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n+        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n+        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+\n+    def test_each_command_position_gets_one_recovery(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)  # First loss: IP command.\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n+        self.prompt(commander)  # Second loss: allowaccess command.\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n+        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n+\n+    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n+        for explicit_policy in (False, True):\n+            with self.subTest(explicit_policy=explicit_policy):\n+                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n+                commander, terminal, feature = self.make_commander(\n+                    ip_command=IP_COMMAND if explicit_policy else spec,\n+                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n+                )\n+                feature.on_session_loss = MagicMock()\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n+                    self.prompt(commander)\n+                feature.on_session_loss.assert_not_called()\n+                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n+\n+    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n+        spec = CommandSpec(\n+            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n+            context_loss=ContextLossAction.RESTART_BLOCK,\n+        )\n+        commander, _terminal, feature = self.make_commander(ip_command=spec)\n+        feature.on_session_loss = MagicMock()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        feature.on_session_loss.assert_not_called()\n+\n+    def test_partial_scope_is_aborted_once_before_replay(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n+        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n+        self.prompt(commander)\n+        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertNotIn(\"abort\", feature.executed)\n+        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n+\n+    def test_failed_context_reset_does_not_loop(self):\n+        commander, terminal, _feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")\n+        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n+            self.prompt(commander, \"interface\")\n+        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n+\n+    def test_session_loss_during_context_reset_resumes_after_login(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n+\n+    def test_cleanup_session_loss_is_bounded(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock())\n+        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n+        commander.register_cleanup(feature, CleanupAction(\n+            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n+        ))\n+        commander.start([feature])\n+        self.prompt(commander)\n+        self.prompt(commander)  # Begin cleanup after the feature completes.\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n+\n+    def test_newly_submitted_block_resets_retry_allowance(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock())\n+        feature = StaticFeature(None, commander, \"two-blocks\", [\n+            ConfigBlock(\"system global\", [\"set alias first\"]),\n+            ConfigBlock(\"system global\", [\"set alias second\"]),\n+        ])\n+        commander.start([feature])\n+        self.prompt(commander)\n+        for _index in range(2):\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander)  # Lost context: retry this block.\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander)  # End this block and start the next one.\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n+        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\nnew file mode 100644\nindex 0000000..56ce729\n--- /dev/null\n+++ b/fortinet/tests/test_common_scope_errors.py\n@@ -0,0 +1,154 @@\n+\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n+)\n+from fortinet.common.common import FOSCliState  # noqa: E402\n+from fortinet.common.features.base import Feature  # noqa: E402\n+from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n+from fortinet.common.terminal import Data  # noqa: E402\n+\n+\n+class RecordingFeature(Feature):\n+    def __init__(self, commander, name, commands):\n+        super().__init__(None, commander, name)\n+        self.commands = commands\n+        self.executed = []\n+\n+    def activate(self):\n+        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n+\n+    def on_command_executed(self, attempt, state):\n+        self.executed.append(attempt.spec.line)\n+\n+\n+class ScopeCommitFailureTests(unittest.TestCase):\n+    @staticmethod\n+    def prompt(commander, context=None, output=b\"\"):\n+        scope = f\" ({context})\" if context else \"\"\n+        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n+            output + f\"fw{scope} #\".encode()\n+        ))\n+\n+    @staticmethod\n+    def writes(terminal):\n+        return [call.args[0] for call in terminal.write.call_args_list]\n+\n+    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n+        for close in (\"next\", \"end\"):\n+            for capture in (False, True):\n+                for best_effort in (False, True):\n+                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n+                        terminal = MagicMock()\n+                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n+                        feature = RecordingFeature(commander, \"commit\", [\n+                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n+                            \"set must-not-run 1\",\n+                        ])\n+                        feature.on_context_loss = MagicMock()\n+                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n+                        commander.start([feature, following])\n+                        self.prompt(commander, \"port1\")\n+                        # The failure code can span multiple serial reads.\n+                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n+                            data = Data(chunk)\n+                            commander.on_output(data)\n+                            self.assertTrue(data.discarded)\n+                        if best_effort:\n+                            self.prompt(commander, \"interface\")\n+                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n+                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n+                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n+                        else:\n+                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n+                                self.prompt(commander, \"interface\")\n+                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n+                        feature.on_context_loss.assert_not_called()\n+                        self.assertEqual(feature.executed, [])\n+                        self.assertFalse(feature.completed)\n+\n+    def test_closing_failure_with_same_prompt_still_ejects(self):\n+        for code in (\"0\", \"7\", \"-61\"):\n+            for suffix in (\"\", \".\"):\n+                with self.subTest(code=code, suffix=suffix):\n+                    terminal = MagicMock()\n+                    commander = FOSCommander(terminal, MagicMock())\n+                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n+                    commander.start([feature])\n+                    self.prompt(commander, \"port1\")\n+                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n+                        self.prompt(\n+                            commander, \"port1\",\n+                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n+                        )\n+                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n+\n+    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n+        for capture in (False, True):\n+            with self.subTest(capture=capture):\n+                terminal = MagicMock()\n+                commander = FOSCommander(terminal, MagicMock())\n+                feature = RecordingFeature(commander, \"configure\", [\n+                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n+                    ])]),\n+                ])\n+                commander.start([feature])\n+                self.prompt(commander)\n+                self.prompt(commander, \"interface\")\n+                self.prompt(commander, \"port1\")\n+                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n+                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n+                self.prompt(commander, \"interface\")\n+                self.prompt(commander)\n+                self.assertTrue(feature.completed)\n+                self.assertTrue(commander.ready)\n+                self.assertEqual(commander.feature_errors, ())\n+\n+    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n+        for best_effort in (False, True):\n+            with self.subTest(best_effort=best_effort):\n+                terminal = MagicMock()\n+                commander = FOSCommander(terminal, MagicMock(), best_effort)\n+                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n+                following = RecordingFeature(commander, \"following\", [\"get status\"])\n+                commander.register_cleanup(feature, CleanupAction(\n+                    \"close\", CommandSequence(\"close\", [\"end\"]),\n+                ))\n+                commander.start([feature, following])\n+                self.prompt(commander)\n+                self.prompt(commander)\n+                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n+                if best_effort:\n+                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n+                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n+                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n+                else:\n+                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n+                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n+                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n+\n+    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n+        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n+            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n+            expected_completion_state=FOSCliState.CMD_PROMPT,\n+        )])\n+        commander.start([feature])\n+        self.prompt(commander, \"interface\")\n+        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n+            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n+        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n+        self.assertFalse(feature.completed)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\nindex 1e31693..d633771 100644\n--- a/fortinet/tests/test_common_stack_boundaries.py\n+++ b/fortinet/tests/test_common_stack_boundaries.py\n@@ -38,15 +38,15 @@ class BoundaryFeature(Feature):\n \n     def on_session_loss(self, attempt):\n         return SessionLossAction.CONTINUE\n \n \n-def make_stack(spec, response, *, allow_recovery=False):\n+def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n     logger = MagicMock()\n     connection = SerialConnection({\n         b\"admin\\r\": b\"Password:\",\n-        b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n         b\"probe\\r\": response,\n     })\n     terminal = Terminal(connection, logger, default_wait=\"fw #\")\n     commander = FOSCommander(terminal, logger)\n     feature = BoundaryFeature(commander, spec)\n@@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):\n     response = (\n         (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n         .encode()\n     )\n     spec = CommandSpec(\"probe\", capture_output=True)\n-    connection, terminal, commander, driver, feature, states = make_stack(spec, response)\n+    connection, terminal, commander, driver, feature, states = make_stack(\n+        spec, response, initial_prompt=prompt.encode()\n+    )\n     try:\n         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n             driver.process_state()\n         assert commander.ready\n@@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b\"\", *, recover=False):\n         completion = (state,)\n     connection, terminal, commander, driver, feature, states = make_stack(\n         CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n         response,\n         allow_recovery=recover,\n+        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n     )\n     try:\n         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n             driver.process_state()\n@@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):\n             self.assertFalse(feature.completed)\n             self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n         finally:\n             terminal.close()\n \n-    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):\n+    def test_idle_read_exposes_retained_prompt_newline(self):\n         connection, terminal, commander, driver, feature, states = make_stack(\n             CommandSpec(\"probe\", capture_output=True), None\n         )\n         try:\n             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n                 driver.process_state()\n             self.assertIn(FOSCliState.TN_TIMEOUT, states)\n-            self.assertEqual(bytes(feature.current_attempt.output), b\"\")\n+            # The login response ended with a newline after the matched CLI\n+            # prompt. Full-buffer timeout inspection exposes that real byte.\n+            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n             self.assertTrue(commander.busy)\n         finally:\n             terminal.close()\n \n     def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n         command_echo = b\"fw (global) # probe\\r\\n\"\n         payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n         response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n         connection, terminal, commander, driver, feature, states = make_stack(\n-            CommandSpec(\"probe\", capture_output=True), response\n+            CommandSpec(\"probe\", capture_output=True), response,\n+            initial_prompt=b\"fw (global) #\",\n         )\n         try:\n             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                 driver.process_state()\ndiff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\nindex 74d6ef7..56346ea 100644\n--- a/fortinet/tests/test_common_stack_parsing.py\n+++ b/fortinet/tests/test_common_stack_parsing.py\n@@ -7,11 +7,13 @@ from pathlib import Path\n from unittest.mock import MagicMock\n \n REPO_ROOT = Path(__file__).resolve().parents[2]\n sys.path.insert(0, str(REPO_ROOT))\n \n-from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n+)\n from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n from fortinet.common.features.base import Feature  # noqa: E402\n from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n from fortinet.common.terminal import Terminal  # noqa: E402\n@@ -35,10 +37,12 @@ class SerialConnection:\n \n     def write(self, data):\n         data = bytes(data)\n         self.writes.append(data)\n         response = self._responses.get(data)\n+        if callable(response):\n+            response = response()\n         if response:\n             chunks = response if isinstance(response, (tuple, list)) else (response,)\n             for chunk in chunks:\n                 if chunk:\n                     self._incoming.put(bytes(chunk))\n@@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):\n         self.assertEqual(bytes(terminal._buffer), b\"\")\n \n     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n         responses = {\n             b\"admin\\r\": b\"Password:\",\n-            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n             b\"get system status\\r\": (\n                 b\"fw (global) # get system status\\r\\n\"\n                 b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n                 b\"--More--\\r\\n\"\n                 b\"Serial-Number: FGVMTEST\\r\\n\"\n@@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):\n         self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n         self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n \n+    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n+        ip_responses = iter([\n+            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n+            b\"fw (port1) (Interim)#\\r\\n\",\n+        ])\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n+            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n+            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n+            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n+            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n+            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n+            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n+        }\n+        feature_ref = []\n+\n+        def configured(commander):\n+            feature = RecordingFeature(commander, \"management\", [\n+                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n+                ])]),\n+            ])\n+            feature_ref.append(feature)\n+            return [feature]\n+\n+        connection, terminal, commander, driver = self.make_stack(configured, responses)\n+        try:\n+            driver.process_state()\n+            self.assertTrue(commander.ready)\n+            self.assertTrue(feature_ref[0].completed)\n+            self.assertEqual(connection.writes, [\n+                b\"admin\\r\", b\"secret\\r\",\n+                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n+                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n+                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n+            ])\n+        finally:\n+            terminal.close()\n+\n+    def test_failed_next_ejects_before_end_through_serial_driver(self):\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n+            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n+            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n+            b\"next\\r\": (\n+                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n+            ),\n+        }\n+        feature_ref = []\n+\n+        def configured(commander):\n+            feature = RecordingFeature(commander, \"management\", [\n+                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n+            ])\n+            feature_ref.append(feature)\n+            return [feature]\n+\n+        connection, terminal, commander, driver = self.make_stack(configured, responses)\n+        try:\n+            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n+                driver.process_state()\n+            self.assertEqual(connection.writes, [\n+                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n+                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n+            ])\n+            self.assertFalse(feature_ref[0].completed)\n+            self.assertFalse(commander.ready)\n+        finally:\n+            terminal.close()\n+\n \n if __name__ == \"__main__\":\n     unittest.main()\ndiff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\nindex 4c0a37b..be7eab4 100644\n--- a/fortinet/tests/test_common_terminal_driver.py\n+++ b/fortinet/tests/test_common_terminal_driver.py\n@@ -9,12 +9,16 @@ from contextlib import contextmanager\n from unittest.mock import MagicMock, patch\n \n REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n sys.path.insert(0, str(REPO_ROOT))\n \n-from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n-from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n+from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n+from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n+from fortinet.common.fos_cli_driver import (  # noqa: E402\n+    FOSCliDriver,\n+    KernelPanicError,\n+)\n from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n \n \n class ByteQueueTests(unittest.TestCase):\n     def test_put_get_close_timeout_and_failure(self):\n@@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):\n         terminal._buffer_limit = 5\n         with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n             terminal._enforce_buffer_limit()\n         terminal._logger.error.assert_called_once()\n \n+    def test_timeout_preserves_partial_token_for_a_later_read(self):\n+        terminal = self.terminal_with_data(b\"Login incor\")\n+        pattern = rb\"(?m)^Login incorrect\\r?$\"\n+        index, match, output = terminal.expect([pattern], timeout=0.001)\n+        self.assertEqual((index, match), (-1, None))\n+        self.assertEqual(bytes(output), b\"Login incor\")\n+        # Inspection without discard keeps the partial token, including when\n+        # another wait expires without receiving any more bytes.\n+        _, _, output = terminal.expect([pattern], timeout=0)\n+        self.assertEqual(bytes(output), b\"Login incor\")\n+        terminal._read_queue.put(b\"rect\\n\")\n+        index, match, output = terminal.expect([pattern], timeout=0.1)\n+        self.assertEqual(index, 0)\n+        self.assertEqual(match.group(), b\"Login incorrect\")\n+        self.assertEqual(bytes(output), b\"Login incorrect\")\n+        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n+\n+    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n+        terminal = self.terminal_with_data(b\"Verifying pass\")\n+        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n+\n+        terminal._read_queue.put(b\"word...\\n\")\n+        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertIsNone(match)\n+        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n+        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n+        output.discard()\n+        self.assertEqual(bytes(terminal._buffer), b\"\")\n+\n+    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n+        prefix = b\"\\nVerifying password...\\n\"\n+        chunk = b\"admin\\nadmin\\n\"\n+        terminal = self.terminal_with_data(chunk)\n+        terminal._buffer.extend(prefix)\n+\n+        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertEqual(bytes(output), prefix + chunk)\n+        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n+        attempt.on_output(output)\n+\n+        self.assertEqual(bytes(attempt.output), prefix + chunk)\n+        self.assertEqual(bytes(terminal._buffer), b\"\")\n+        terminal._logger.warning.assert_not_called()\n+\n     def test_suppression_is_nested_and_restores_context(self):\n         @contextmanager\n         def context():\n             events.append(\"enter\")\n             try:\n@@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):\n         with self.assertRaisesRegex(OSError, \"serial failed\"):\n             queue.get(0)\n         logger.exception.assert_called_once()\n         with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n             self.assertEqual(terminal_buffer_limit_bytes(), 32)\n-        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n+        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n+            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n+        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n             with self.assertRaises(ValueError):\n                 terminal_buffer_limit_bytes()\n \n+    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n+        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n+            with self.subTest(env_name=env_name):\n+                terminal = self.terminal_with_data(b\"matched\")\n+                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n+                    terminal.expect([b\"matched\"], timeout=0.1)\n+                terminal._logger.log.assert_called_once_with(\n+                    TRACE_LEVEL,\n+                    \"buffer: bytearray(b'matched')\",\n+                )\n+\n \n class DriverTests(unittest.TestCase):\n     def make_driver(self, *, allow_recovery=False):\n         terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n         commander.ready = False\n@@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):\n         self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n         terminal.expect.return_value = (-1, None, Data(b\"\"))\n         self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n         driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n \n+    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n+        driver, _, _, logger, *_ = self.make_driver()\n+        terminal = Terminal(MagicMock(), logger)\n+        terminal._ensure_reader = lambda: None\n+        terminal._read_queue.put(b\"partial token\")\n+        driver._terminal = terminal\n+\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n+            state, output, matched = driver._next_state()\n+            self.assertEqual(state, FOSCliState.UNKNOWN)\n+            self.assertEqual(bytes(output), b\"partial token\")\n+            self.assertFalse(matched)\n+            state, output, matched = driver._next_state()\n+            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n+            self.assertEqual(bytes(output), b\"partial token\")\n+            self.assertFalse(matched)\n+\n+    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n+        driver, terminal, commander, *_ = self.make_driver()\n+        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n+        panic = (\n+            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n+            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n+        )\n+\n+        self.assertIsNone(\n+            re.search(\n+                pattern,\n+                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n+            )\n+        )\n+        match = re.search(pattern, panic)\n+        self.assertIsNotNone(match)\n+        terminal.expect.return_value = (\n+            FOSCliState.KERNEL_PANIC.value,\n+            match,\n+            Data(panic),\n+        )\n+\n+        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n+            driver.process_state()\n+\n+        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n+\n \n if __name__ == \"__main__\":\n     unittest.main()",
        "lineStart": 1198,
        "lineEnd": 2108,
        "totalLines": 2108,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716201514,
      "end": 1793716201527
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d1283a0016dlawecUPcb3wa",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d11bcd001Vfv50xKiBoiGMh",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 38022,
    "input": 34457,
    "output": 27,
    "reasoning": 18,
    "cache": {
      "read": 3520,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d11bcd001Vfv50xKiBoiGMh",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716198349,
    "completed": 1793716201535
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 38022,
    "input": 34457,
    "output": 27,
    "reasoning": 18,
    "cache": {
      "read": 3520,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 5
step-start
{
  "type": "step-start",
  "id": "prt_1a1d130530016OMZGecz80BEcl",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d128420016vUfaFoGrZAE1p"
}
Reasoning
Now I have the full diff. The changed paths are 18. Now I need to read the head files to verify correctness. Key files:

1. `fortinet/common/cli_commands.py` (207 lines)
2. `fortinet/common/common.py` (92 lines)
3. `fortinet/common/features/base.py` (119)
4. `fortinet/common/features/credentials.py` (90)
5. `fortinet/common/features/pki.py` (471)
6. `fortinet/common/features/startup_config.py` (117)
7. `fortinet/common/fos_cli_driver.py` (331)
8. `fortinet/common/fos_commander.py` (687)
9. `fortinet/common/launch.py` (506)
10. `fortinet/common/terminal.py` (398)
11. `fortinet/fortigate/README.md` (497)
12. `fortinet/fortigate/docker/README.md` (500)
13. tests: test_common_admin_credentials.py (new), test_common_recovery.py (new), test_common_scope_errors.py (new), test_common_stack_boundaries.py (M), test_common_stack_parsing.py (M), test_common_terminal_driver.py (M)

Let me read head files. Start with cli_commands.py, common.py, fos_commander.py (the biggest change), terminal.py.
I have the full diff. Now let me read the head files to verify the changes in context.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/cli_commands.py"
}

Output

<path>/source/head/fortinet/common/cli_commands.py</path>
<type>file</type>
<content>
1: """Command and scope data used by the FortiOS CLI scheduler."""
2: 
3: from dataclasses import dataclass, field
4: from enum import Enum, auto
5: 
6: from .common import FOSCliState
7: 
8: 
9: class SessionLossAction(Enum):
10:     RESTART_BLOCK = auto()
11:     COMPLETE_BLOCK = auto()
12:     CONTINUE = auto()
13:     VALIDATE = auto()
14:     FAIL = auto()
15: 
16: 
17: class ContextLossAction(Enum):
18:     RESTART_BLOCK = auto()
19:     FAIL = auto()
20: 
21: 
22: @dataclass(frozen=True, init=False)
23: class CommandSpec:
24:     line: str
25:     completion_states: tuple = ()
26:     capture_output: bool = False
27:     suppress_output: bool = False
28:     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK
29:     expected_completion_state: object = None
30:     fail_on_error: bool = False
31:     context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK
32:     continuation: bool = False
33: 
34:     def __init__(self, line, completion_states=(), capture_output=False,
35:                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,
36:                  expected_completion_state=None, fail_on_error=False,
37:                  context_loss=None, continuation=False):
38:         object.__setattr__(self, "line", line)
39:         object.__setattr__(self, "completion_states", completion_states)
40:         object.__setattr__(self, "capture_output", capture_output)
41:         object.__setattr__(self, "suppress_output", suppress_output)
42:         object.__setattr__(self, "session_loss", session_loss)
43:         object.__setattr__(self, "expected_completion_state", expected_completion_state)
44:         object.__setattr__(self, "fail_on_error", fail_on_error)
45:         object.__setattr__(self, "continuation", continuation)
46:         if context_loss is None:
47:             # Commands that must not replay after logout must not replay after
48:             # an unexpected scope exit either. Features can override this policy.
49:             context_loss = (
50:                 ContextLossAction.RESTART_BLOCK
51:                 if session_loss == SessionLossAction.RESTART_BLOCK
52:                 else ContextLossAction.FAIL
53:             )
54:         object.__setattr__(self, "context_loss", context_loss)
55:         self.__post_init__()
56: 
57:     def __post_init__(self):
58:         if "\r" in self.line or "\n" in self.line:
59:             raise ValueError("CLI commands must contain exactly one line")
60: 
61:     @property
62:     def closes_scope(self):
63:         return not self.continuation and self.line.strip().lower() in {"next", "end"}
64: 
65: 
66: @dataclass
67: class CommandAttempt:
68:     spec: CommandSpec
69:     number: int
70:     session_epoch: int
71:     output: bytearray = field(default_factory=bytearray)
72:     prompt_context_before: tuple | None = None
73:     prompt_context_after: tuple | None = None
74:     block_index: int | None = None
75:     retry_count: int = 0
76: 
77:     def on_output(self, output):
78:         if not (self.spec.capture_output or self.spec.closes_scope):
79:             return False
80:         data = bytes(output)
81:         self.output.extend(data)
82:         output.discard(data)
83:         return True
84: 
85: 
86: class Scope:
87:     def __init__(self, value, children=()):
88:         self.value = value
89:         self.children = list(children)
90: 
91:     @property
92:     def open_line(self):
93:         raise NotImplementedError
94: 
95:     @property
96:     def close_line(self):
97:         raise NotImplementedError
98: 
99:     def flatten(self):
100:         commands = flatten_commands(self.open_line)
101:         for child in self.children:
102:             commands.extend(flatten_commands(child))
103:         commands.append(CommandSpec(self.close_line))
104:         return commands
105: 
106: 
107: class ConfigBlock(Scope):
108:     @property
109:     def open_line(self):
110:         return f"config {self.value}"
111: 
112:     @property
113:     def close_line(self):
114:         return "end"
115: 
116: 
117: class EditBlock(Scope):
118:     @property
119:     def open_line(self):
120:         return f"edit {self.value}"
121: 
122:     @property
123:     def close_line(self):
124:         return "next"
125: 
126: 
127: class SetValue:
128:     """A quoted ``set`` command supporting FortiOS continuation prompts."""
129: 
130:     def __init__(self, field, value, fail_on_error=True, validate_prompt=True):
131:         self.field = field
132:         self.value = value
133:         self.fail_on_error = fail_on_error
134:         self.validate_prompt = validate_prompt
135: 
136:     def flatten(self):
137:         lines = str(self.value).strip().splitlines() or [""]
138:         lines[0] = f'set {self.field} "{lines[0]}'
139:         lines[-1] += '"'
140:         return _flatten_quoted_lines(
141:             lines, fail_on_error=self.fail_on_error,
142:             validate_prompt=self.validate_prompt,
143:         )
144: 
145: 
146: def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):
147:     """Send a logical command one line per continuation prompt, without re-quoting."""
148:     commands = []
149:     for index, line in enumerate(lines):
150:         last_line = index == len(lines) - 1
151:         expected = (
152:             FOSCliState.CMD_PROMPT if last_line
153:             else FOSCliState.MULTILINE_PROMPT
154:         )
155:         completion_states = ()
156:         if len(lines) > 1:
157:             completion_states = (
158:                 (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)
159:                 if last_line else
160:                 (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
161:             )
162:         commands.append(CommandSpec(
163:             line,
164:             completion_states=completion_states,
165:             capture_output=True,
166:             expected_completion_state=expected if validate_prompt else None,
167:             fail_on_error=fail_on_error,
168:             continuation=index > 0,
169:         ))
170:     return commands
171: 
172: 
173: class CommandSequence:
174:     """An unscoped workflow container; it does not emit CLI framing."""
175: 
176:     def __init__(self, name, children=()):
177:         self.name = name
178:         self.children = list(children)
179: 
180:     def flatten(self):
181:         commands = []
182:         for child in self.children:
183:             commands.extend(flatten_commands(child))
184:         return commands
185: 
186: 
187: def flatten_commands(value):
188:     """Flatten command containers and wrap plain CLI lines with defaults."""
189:     if isinstance(value, str):
190:         if "\n" in value:
191:             return _flatten_quoted_lines(value.split("\n"))
192:         return [CommandSpec(value)]
193:     if isinstance(value, CommandSpec):
194:         return [value]
195:     if isinstance(value, (Scope, CommandSequence, SetValue)):
196:         return value.flatten()
197:     raise TypeError(
198:         "Commands must be strings, CommandSpec instances, or command containers"
199:     )
200: 
201: 
202: @dataclass(frozen=True)
203: class CleanupAction:
204:     name: str
205:     block: object
206:     on_completion: bool = True
207:     on_interruption: bool = True

(End of file - total 207 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d1367a001ukE2cc5NswRagM",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d128420016vUfaFoGrZAE1p",
  "callID": "call_c175eec363294779a4cb88aa",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/cli_commands.py"
    },
    "output": "<path>/source/head/fortinet/common/cli_commands.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n2: \n3: from dataclasses import dataclass, field\n4: from enum import Enum, auto\n5: \n6: from .common import FOSCliState\n7: \n8: \n9: class SessionLossAction(Enum):\n10:     RESTART_BLOCK = auto()\n11:     COMPLETE_BLOCK = auto()\n12:     CONTINUE = auto()\n13:     VALIDATE = auto()\n14:     FAIL = auto()\n15: \n16: \n17: class ContextLossAction(Enum):\n18:     RESTART_BLOCK = auto()\n19:     FAIL = auto()\n20: \n21: \n22: @dataclass(frozen=True, init=False)\n23: class CommandSpec:\n24:     line: str\n25:     completion_states: tuple = ()\n26:     capture_output: bool = False\n27:     suppress_output: bool = False\n28:     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n29:     expected_completion_state: object = None\n30:     fail_on_error: bool = False\n31:     context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n32:     continuation: bool = False\n33: \n34:     def __init__(self, line, completion_states=(), capture_output=False,\n35:                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n36:                  expected_completion_state=None, fail_on_error=False,\n37:                  context_loss=None, continuation=False):\n38:         object.__setattr__(self, \"line\", line)\n39:         object.__setattr__(self, \"completion_states\", completion_states)\n40:         object.__setattr__(self, \"capture_output\", capture_output)\n41:         object.__setattr__(self, \"suppress_output\", suppress_output)\n42:         object.__setattr__(self, \"session_loss\", session_loss)\n43:         object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n44:         object.__setattr__(self, \"fail_on_error\", fail_on_error)\n45:         object.__setattr__(self, \"continuation\", continuation)\n46:         if context_loss is None:\n47:             # Commands that must not replay after logout must not replay after\n48:             # an unexpected scope exit either. Features can override this policy.\n49:             context_loss = (\n50:                 ContextLossAction.RESTART_BLOCK\n51:                 if session_loss == SessionLossAction.RESTART_BLOCK\n52:                 else ContextLossAction.FAIL\n53:             )\n54:         object.__setattr__(self, \"context_loss\", context_loss)\n55:         self.__post_init__()\n56: \n57:     def __post_init__(self):\n58:         if \"\\r\" in self.line or \"\\n\" in self.line:\n59:             raise ValueError(\"CLI commands must contain exactly one line\")\n60: \n61:     @property\n62:     def closes_scope(self):\n63:         return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n64: \n65: \n66: @dataclass\n67: class CommandAttempt:\n68:     spec: CommandSpec\n69:     number: int\n70:     session_epoch: int\n71:     output: bytearray = field(default_factory=bytearray)\n72:     prompt_context_before: tuple | None = None\n73:     prompt_context_after: tuple | None = None\n74:     block_index: int | None = None\n75:     retry_count: int = 0\n76: \n77:     def on_output(self, output):\n78:         if not (self.spec.capture_output or self.spec.closes_scope):\n79:             return False\n80:         data = bytes(output)\n81:         self.output.extend(data)\n82:         output.discard(data)\n83:         return True\n84: \n85: \n86: class Scope:\n87:     def __init__(self, value, children=()):\n88:         self.value = value\n89:         self.children = list(children)\n90: \n91:     @property\n92:     def open_line(self):\n93:         raise NotImplementedError\n94: \n95:     @property\n96:     def close_line(self):\n97:         raise NotImplementedError\n98: \n99:     def flatten(self):\n100:         commands = flatten_commands(self.open_line)\n101:         for child in self.children:\n102:             commands.extend(flatten_commands(child))\n103:         commands.append(CommandSpec(self.close_line))\n104:         return commands\n105: \n106: \n107: class ConfigBlock(Scope):\n108:     @property\n109:     def open_line(self):\n110:         return f\"config {self.value}\"\n111: \n112:     @property\n113:     def close_line(self):\n114:         return \"end\"\n115: \n116: \n117: class EditBlock(Scope):\n118:     @property\n119:     def open_line(self):\n120:         return f\"edit {self.value}\"\n121: \n122:     @property\n123:     def close_line(self):\n124:         return \"next\"\n125: \n126: \n127: class SetValue:\n128:     \"\"\"A quoted ``set`` command supporting FortiOS continuation prompts.\"\"\"\n129: \n130:     def __init__(self, field, value, fail_on_error=True, validate_prompt=True):\n131:         self.field = field\n132:         self.value = value\n133:         self.fail_on_error = fail_on_error\n134:         self.validate_prompt = validate_prompt\n135: \n136:     def flatten(self):\n137:         lines = str(self.value).strip().splitlines() or [\"\"]\n138:         lines[0] = f'set {self.field} \"{lines[0]}'\n139:         lines[-1] += '\"'\n140:         return _flatten_quoted_lines(\n141:             lines, fail_on_error=self.fail_on_error,\n142:             validate_prompt=self.validate_prompt,\n143:         )\n144: \n145: \n146: def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n147:     \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n148:     commands = []\n149:     for index, line in enumerate(lines):\n150:         last_line = index == len(lines) - 1\n151:         expected = (\n152:             FOSCliState.CMD_PROMPT if last_line\n153:             else FOSCliState.MULTILINE_PROMPT\n154:         )\n155:         completion_states = ()\n156:         if len(lines) > 1:\n157:             completion_states = (\n158:                 (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n159:                 if last_line else\n160:                 (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n161:             )\n162:         commands.append(CommandSpec(\n163:             line,\n164:             completion_states=completion_states,\n165:             capture_output=True,\n166:             expected_completion_state=expected if validate_prompt else None,\n167:             fail_on_error=fail_on_error,\n168:             continuation=index > 0,\n169:         ))\n170:     return commands\n171: \n172: \n173: class CommandSequence:\n174:     \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n175: \n176:     def __init__(self, name, children=()):\n177:         self.name = name\n178:         self.children = list(children)\n179: \n180:     def flatten(self):\n181:         commands = []\n182:         for child in self.children:\n183:             commands.extend(flatten_commands(child))\n184:         return commands\n185: \n186: \n187: def flatten_commands(value):\n188:     \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n189:     if isinstance(value, str):\n190:         if \"\\n\" in value:\n191:             return _flatten_quoted_lines(value.split(\"\\n\"))\n192:         return [CommandSpec(value)]\n193:     if isinstance(value, CommandSpec):\n194:         return [value]\n195:     if isinstance(value, (Scope, CommandSequence, SetValue)):\n196:         return value.flatten()\n197:     raise TypeError(\n198:         \"Commands must be strings, CommandSpec instances, or command containers\"\n199:     )\n200: \n201: \n202: @dataclass(frozen=True)\n203: class CleanupAction:\n204:     name: str\n205:     block: object\n206:     on_completion: bool = True\n207:     on_interruption: bool = True\n\n(End of file - total 207 lines)\n</content>",
    "title": "source/head/fortinet/common/cli_commands.py",
    "metadata": {
      "preview": "\"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\n\nfrom .common import FOSCliState\n\n\nclass SessionLossAction(Enum):\n    RESTART_BLOCK = auto()\n    COMPLETE_BLOCK = auto()\n    CONTINUE = auto()\n    VALIDATE = auto()\n    FAIL = auto()\n\n\nclass ContextLossAction(Enum):\n    RESTART_BLOCK = auto()\n    FAIL = auto()\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/cli_commands.py",
        "text": "\"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\n\nfrom .common import FOSCliState\n\n\nclass SessionLossAction(Enum):\n    RESTART_BLOCK = auto()\n    COMPLETE_BLOCK = auto()\n    CONTINUE = auto()\n    VALIDATE = auto()\n    FAIL = auto()\n\n\nclass ContextLossAction(Enum):\n    RESTART_BLOCK = auto()\n    FAIL = auto()\n\n\n@dataclass(frozen=True, init=False)\nclass CommandSpec:\n    line: str\n    completion_states: tuple = ()\n    capture_output: bool = False\n    suppress_output: bool = False\n    session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n    expected_completion_state: object = None\n    fail_on_error: bool = False\n    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n    continuation: bool = False\n\n    def __init__(self, line, completion_states=(), capture_output=False,\n                 suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n                 expected_completion_state=None, fail_on_error=False,\n                 context_loss=None, continuation=False):\n        object.__setattr__(self, \"line\", line)\n        object.__setattr__(self, \"completion_states\", completion_states)\n        object.__setattr__(self, \"capture_output\", capture_output)\n        object.__setattr__(self, \"suppress_output\", suppress_output)\n        object.__setattr__(self, \"session_loss\", session_loss)\n        object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n        object.__setattr__(self, \"fail_on_error\", fail_on_error)\n        object.__setattr__(self, \"continuation\", continuation)\n        if context_loss is None:\n            # Commands that must not replay after logout must not replay after\n            # an unexpected scope exit either. Features can override this policy.\n            context_loss = (\n                ContextLossAction.RESTART_BLOCK\n                if session_loss == SessionLossAction.RESTART_BLOCK\n                else ContextLossAction.FAIL\n            )\n        object.__setattr__(self, \"context_loss\", context_loss)\n        self.__post_init__()\n\n    def __post_init__(self):\n        if \"\\r\" in self.line or \"\\n\" in self.line:\n            raise ValueError(\"CLI commands must contain exactly one line\")\n\n    @property\n    def closes_scope(self):\n        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n\n\n@dataclass\nclass CommandAttempt:\n    spec: CommandSpec\n    number: int\n    session_epoch: int\n    output: bytearray = field(default_factory=bytearray)\n    prompt_context_before: tuple | None = None\n    prompt_context_after: tuple | None = None\n    block_index: int | None = None\n    retry_count: int = 0\n\n    def on_output(self, output):\n        if not (self.spec.capture_output or self.spec.closes_scope):\n            return False\n        data = bytes(output)\n        self.output.extend(data)\n        output.discard(data)\n        return True\n\n\nclass Scope:\n    def __init__(self, value, children=()):\n        self.value = value\n        self.children = list(children)\n\n    @property\n    def open_line(self):\n        raise NotImplementedError\n\n    @property\n    def close_line(self):\n        raise NotImplementedError\n\n    def flatten(self):\n        commands = flatten_commands(self.open_line)\n        for child in self.children:\n            commands.extend(flatten_commands(child))\n        commands.append(CommandSpec(self.close_line))\n        return commands\n\n\nclass ConfigBlock(Scope):\n    @property\n    def open_line(self):\n        return f\"config {self.value}\"\n\n    @property\n    def close_line(self):\n        return \"end\"\n\n\nclass EditBlock(Scope):\n    @property\n    def open_line(self):\n        return f\"edit {self.value}\"\n\n    @property\n    def close_line(self):\n        return \"next\"\n\n\nclass SetValue:\n    \"\"\"A quoted ``set`` command supporting FortiOS continuation prompts.\"\"\"\n\n    def __init__(self, field, value, fail_on_error=True, validate_prompt=True):\n        self.field = field\n        self.value = value\n        self.fail_on_error = fail_on_error\n        self.validate_prompt = validate_prompt\n\n    def flatten(self):\n        lines = str(self.value).strip().splitlines() or [\"\"]\n        lines[0] = f'set {self.field} \"{lines[0]}'\n        lines[-1] += '\"'\n        return _flatten_quoted_lines(\n            lines, fail_on_error=self.fail_on_error,\n            validate_prompt=self.validate_prompt,\n        )\n\n\ndef _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n    commands = []\n    for index, line in enumerate(lines):\n        last_line = index == len(lines) - 1\n        expected = (\n            FOSCliState.CMD_PROMPT if last_line\n            else FOSCliState.MULTILINE_PROMPT\n        )\n        completion_states = ()\n        if len(lines) > 1:\n            completion_states = (\n                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n                if last_line else\n                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n            )\n        commands.append(CommandSpec(\n            line,\n            completion_states=completion_states,\n            capture_output=True,\n            expected_completion_state=expected if validate_prompt else None,\n            fail_on_error=fail_on_error,\n            continuation=index > 0,\n        ))\n    return commands\n\n\nclass CommandSequence:\n    \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n\n    def __init__(self, name, children=()):\n        self.name = name\n        self.children = list(children)\n\n    def flatten(self):\n        commands = []\n        for child in self.children:\n            commands.extend(flatten_commands(child))\n        return commands\n\n\ndef flatten_commands(value):\n    \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n    if isinstance(value, str):\n        if \"\\n\" in value:\n            return _flatten_quoted_lines(value.split(\"\\n\"))\n        return [CommandSpec(value)]\n    if isinstance(value, CommandSpec):\n        return [value]\n    if isinstance(value, (Scope, CommandSequence, SetValue)):\n        return value.flatten()\n    raise TypeError(\n        \"Commands must be strings, CommandSpec instances, or command containers\"\n    )\n\n\n@dataclass(frozen=True)\nclass CleanupAction:\n    name: str\n    block: object\n    on_completion: bool = True\n    on_interruption: bool = True",
        "lineStart": 1,
        "lineEnd": 207,
        "totalLines": 207,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716205183,
      "end": 1793716205190
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/common.py"
}

Output

<path>/source/head/fortinet/common/common.py</path>
<type>file</type>
<content>
1: from enum import IntEnum, auto
2: from functools import wraps
3: from time import perf_counter
4: 
5: 
6: TRACE_LEVEL = 9
7: 
8: 
9: class FOSCliState(IntEnum):
10:     PROVIDE_USERNAME = 0
11:     PROVIDE_PASSWORD = auto()
12:     CHANGE_PASSWORD = auto()
13:     CREDENTIAL_REJECTED = auto()
14:     CREDENTIAL_ACCEPTED = auto()
15:     LIC_FAIL = auto()
16:     CMD_PROMPT = auto()
17:     CMD_PROMPT_ECHO = auto()
18:     SHUTTING_DOWN = auto()
19:     REBOOTING = auto()
20:     SESSION_LOST = auto()
21:     CURRENT_PASSWORD = auto()
22:     CONFIRMATION = auto()
23:     CHANGE_PASSWORD_CONFIRM = auto()
24:     MORE_PROMPT = auto()
25:     MULTILINE_PROMPT = auto()
26:     KERNEL_PANIC = auto()
27:     UNKNOWN = auto()  # Non-patterns from here on.
28:     TN_TIMEOUT = auto()
29: 
30: 
31: GENERIC_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+"
32: DEFAULT_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+(?:-VM64)?-KVM(?:-[A-Za-z0-9]*)?"
33: LICENSED_HOSTNAME_REGEX = rb"[A-Z][A-Z0-9]{7,}"
34: BOOTSTRAP_HOSTNAME_REGEX = (
35:     rb"(?:" + GENERIC_HOSTNAME_REGEX + rb"|" + DEFAULT_HOSTNAME_REGEX + rb"|" + LICENSED_HOSTNAME_REGEX + rb")"
36: )
37: PROMPT_CONTEXT_REGEX = rb"(?:[ \t]+\([^)]+\))*"
38: DEFAULT_HOSTNAME_PROMPT = rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*\r?$"
39: DEFAULT_HOSTNAME_PROMPT_ECHO = rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*[^\r\n]+(?:\r?\n)?"
40: 
41: FOS_CLI_STATE_PATTERNS = [None] * FOSCliState.UNKNOWN.value
42: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_USERNAME.value] = (
43:         rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX +
44:         rb"(?:\((?:Primary|Secondary)\))?"
45:         rb"[ \t]+login:[ \t]*"
46: )
47: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD.value] = rb"(?m)^New Password:[ \t]*"
48: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_PASSWORD.value] = rb"(?m)^Password:[ \t]*"
49: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_REJECTED.value] = rb"(?m)^Login incorrect\r?$"
50: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_ACCEPTED.value] = rb"(?m)^Welcome ?!\r?$"
51: FOS_CLI_STATE_PATTERNS[FOSCliState.LIC_FAIL.value] = rb"(?mi)^VM license install failed\.?\r?$"
52: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT.value] = DEFAULT_HOSTNAME_PROMPT
53: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT_ECHO.value] = DEFAULT_HOSTNAME_PROMPT_ECHO
54: FOS_CLI_STATE_PATTERNS[FOSCliState.SHUTTING_DOWN.value] = b"system is going down"
55: FOS_CLI_STATE_PATTERNS[FOSCliState.REBOOTING.value] = b"stand by while rebooting"
56: FOS_CLI_STATE_PATTERNS[FOSCliState.SESSION_LOST.value] = (
57:     rb"\*ATTENTION\*: Admin sessions removed because license registration status changed.*"
58: )
59: FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (
60:     rb"(?mi)(?:Please enter current administrator password|Current Password):?\s*"
61: )
62: FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb"(?mi)Do you want to continue\?"
63: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb"(?mi)^Confirm Password:[ \t]*"
64: FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb"--More--\s*"
65: FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb"(?m)^>[ \t]*\r?$"
66: FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (
67:     rb"(?mi)^Kernel panic(?: - not syncing)?:[^\r\n]*\r?\n"
68:     rb"CPU: [0-9]+ PID: [0-9]+ Comm: [^\r\n]+"
69: )
70: 
71: DEF_POLICY_COMPLIANT_PASSWORD = "FortinetFOS1!"
72: DEFAULT_USERNAME = "admin"
73: DEFAULT_PASSWORD = DEFAULT_USERNAME
74: 
75: 
76: class Credentials:
77:     def __init__(self, username, password) -> None:
78:         super().__init__()
79:         self.username = username
80:         self.password = password
81: 
82: 
83: def timed(fn):
84:     @wraps(fn)
85:     def wrapper(*args, **kwargs):
86:         started = perf_counter()
87:         try:
88:             return fn(*args, **kwargs)
89:         finally:
90:             print(f"{fn.__qualname__}: {perf_counter() - started:.3f}s")
91: 
92:     return wrapper

(End of file - total 92 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d136b0001gBm5rmxpttuMQZ",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d128420016vUfaFoGrZAE1p",
  "callID": "call_5390e9758e704f8aafd4acb1",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/common.py"
    },
    "output": "<path>/source/head/fortinet/common/common.py</path>\n<type>file</type>\n<content>\n1: from enum import IntEnum, auto\n2: from functools import wraps\n3: from time import perf_counter\n4: \n5: \n6: TRACE_LEVEL = 9\n7: \n8: \n9: class FOSCliState(IntEnum):\n10:     PROVIDE_USERNAME = 0\n11:     PROVIDE_PASSWORD = auto()\n12:     CHANGE_PASSWORD = auto()\n13:     CREDENTIAL_REJECTED = auto()\n14:     CREDENTIAL_ACCEPTED = auto()\n15:     LIC_FAIL = auto()\n16:     CMD_PROMPT = auto()\n17:     CMD_PROMPT_ECHO = auto()\n18:     SHUTTING_DOWN = auto()\n19:     REBOOTING = auto()\n20:     SESSION_LOST = auto()\n21:     CURRENT_PASSWORD = auto()\n22:     CONFIRMATION = auto()\n23:     CHANGE_PASSWORD_CONFIRM = auto()\n24:     MORE_PROMPT = auto()\n25:     MULTILINE_PROMPT = auto()\n26:     KERNEL_PANIC = auto()\n27:     UNKNOWN = auto()  # Non-patterns from here on.\n28:     TN_TIMEOUT = auto()\n29: \n30: \n31: GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n32: DEFAULT_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+(?:-VM64)?-KVM(?:-[A-Za-z0-9]*)?\"\n33: LICENSED_HOSTNAME_REGEX = rb\"[A-Z][A-Z0-9]{7,}\"\n34: BOOTSTRAP_HOSTNAME_REGEX = (\n35:     rb\"(?:\" + GENERIC_HOSTNAME_REGEX + rb\"|\" + DEFAULT_HOSTNAME_REGEX + rb\"|\" + LICENSED_HOSTNAME_REGEX + rb\")\"\n36: )\n37: PROMPT_CONTEXT_REGEX = rb\"(?:[ \\t]+\\([^)]+\\))*\"\n38: DEFAULT_HOSTNAME_PROMPT = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n39: DEFAULT_HOSTNAME_PROMPT_ECHO = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n40: \n41: FOS_CLI_STATE_PATTERNS = [None] * FOSCliState.UNKNOWN.value\n42: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_USERNAME.value] = (\n43:         rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX +\n44:         rb\"(?:\\((?:Primary|Secondary)\\))?\"\n45:         rb\"[ \\t]+login:[ \\t]*\"\n46: )\n47: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD.value] = rb\"(?m)^New Password:[ \\t]*\"\n48: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_PASSWORD.value] = rb\"(?m)^Password:[ \\t]*\"\n49: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_REJECTED.value] = rb\"(?m)^Login incorrect\\r?$\"\n50: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_ACCEPTED.value] = rb\"(?m)^Welcome ?!\\r?$\"\n51: FOS_CLI_STATE_PATTERNS[FOSCliState.LIC_FAIL.value] = rb\"(?mi)^VM license install failed\\.?\\r?$\"\n52: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT.value] = DEFAULT_HOSTNAME_PROMPT\n53: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT_ECHO.value] = DEFAULT_HOSTNAME_PROMPT_ECHO\n54: FOS_CLI_STATE_PATTERNS[FOSCliState.SHUTTING_DOWN.value] = b\"system is going down\"\n55: FOS_CLI_STATE_PATTERNS[FOSCliState.REBOOTING.value] = b\"stand by while rebooting\"\n56: FOS_CLI_STATE_PATTERNS[FOSCliState.SESSION_LOST.value] = (\n57:     rb\"\\*ATTENTION\\*: Admin sessions removed because license registration status changed.*\"\n58: )\n59: FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n60:     rb\"(?mi)(?:Please enter current administrator password|Current Password):?\\s*\"\n61: )\n62: FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n63: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n64: FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n65: FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n66: FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n67:     rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n68:     rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n69: )\n70: \n71: DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n72: DEFAULT_USERNAME = \"admin\"\n73: DEFAULT_PASSWORD = DEFAULT_USERNAME\n74: \n75: \n76: class Credentials:\n77:     def __init__(self, username, password) -> None:\n78:         super().__init__()\n79:         self.username = username\n80:         self.password = password\n81: \n82: \n83: def timed(fn):\n84:     @wraps(fn)\n85:     def wrapper(*args, **kwargs):\n86:         started = perf_counter()\n87:         try:\n88:             return fn(*args, **kwargs)\n89:         finally:\n90:             print(f\"{fn.__qualname__}: {perf_counter() - started:.3f}s\")\n91: \n92:     return wrapper\n\n(End of file - total 92 lines)\n</content>",
    "title": "source/head/fortinet/common/common.py",
    "metadata": {
      "preview": "from enum import IntEnum, auto\nfrom functools import wraps\nfrom time import perf_counter\n\n\nTRACE_LEVEL = 9\n\n\nclass FOSCliState(IntEnum):\n    PROVIDE_USERNAME = 0\n    PROVIDE_PASSWORD = auto()\n    CHANGE_PASSWORD = auto()\n    CREDENTIAL_REJECTED = auto()\n    CREDENTIAL_ACCEPTED = auto()\n    LIC_FAIL = auto()\n    CMD_PROMPT = auto()\n    CMD_PROMPT_ECHO = auto()\n    SHUTTING_DOWN = auto()\n    REBOOTING = auto()\n    SESSION_LOST = auto()",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/common.py",
        "text": "from enum import IntEnum, auto\nfrom functools import wraps\nfrom time import perf_counter\n\n\nTRACE_LEVEL = 9\n\n\nclass FOSCliState(IntEnum):\n    PROVIDE_USERNAME = 0\n    PROVIDE_PASSWORD = auto()\n    CHANGE_PASSWORD = auto()\n    CREDENTIAL_REJECTED = auto()\n    CREDENTIAL_ACCEPTED = auto()\n    LIC_FAIL = auto()\n    CMD_PROMPT = auto()\n    CMD_PROMPT_ECHO = auto()\n    SHUTTING_DOWN = auto()\n    REBOOTING = auto()\n    SESSION_LOST = auto()\n    CURRENT_PASSWORD = auto()\n    CONFIRMATION = auto()\n    CHANGE_PASSWORD_CONFIRM = auto()\n    MORE_PROMPT = auto()\n    MULTILINE_PROMPT = auto()\n    KERNEL_PANIC = auto()\n    UNKNOWN = auto()  # Non-patterns from here on.\n    TN_TIMEOUT = auto()\n\n\nGENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\nDEFAULT_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+(?:-VM64)?-KVM(?:-[A-Za-z0-9]*)?\"\nLICENSED_HOSTNAME_REGEX = rb\"[A-Z][A-Z0-9]{7,}\"\nBOOTSTRAP_HOSTNAME_REGEX = (\n    rb\"(?:\" + GENERIC_HOSTNAME_REGEX + rb\"|\" + DEFAULT_HOSTNAME_REGEX + rb\"|\" + LICENSED_HOSTNAME_REGEX + rb\")\"\n)\nPROMPT_CONTEXT_REGEX = rb\"(?:[ \\t]+\\([^)]+\\))*\"\nDEFAULT_HOSTNAME_PROMPT = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\nDEFAULT_HOSTNAME_PROMPT_ECHO = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n\nFOS_CLI_STATE_PATTERNS = [None] * FOSCliState.UNKNOWN.value\nFOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_USERNAME.value] = (\n        rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX +\n        rb\"(?:\\((?:Primary|Secondary)\\))?\"\n        rb\"[ \\t]+login:[ \\t]*\"\n)\nFOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD.value] = rb\"(?m)^New Password:[ \\t]*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_PASSWORD.value] = rb\"(?m)^Password:[ \\t]*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_REJECTED.value] = rb\"(?m)^Login incorrect\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_ACCEPTED.value] = rb\"(?m)^Welcome ?!\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.LIC_FAIL.value] = rb\"(?mi)^VM license install failed\\.?\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT.value] = DEFAULT_HOSTNAME_PROMPT\nFOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT_ECHO.value] = DEFAULT_HOSTNAME_PROMPT_ECHO\nFOS_CLI_STATE_PATTERNS[FOSCliState.SHUTTING_DOWN.value] = b\"system is going down\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.REBOOTING.value] = b\"stand by while rebooting\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.SESSION_LOST.value] = (\n    rb\"\\*ATTENTION\\*: Admin sessions removed because license registration status changed.*\"\n)\nFOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n    rb\"(?mi)(?:Please enter current administrator password|Current Password):?\\s*\"\n)\nFOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n)\n\nDEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\nDEFAULT_USERNAME = \"admin\"\nDEFAULT_PASSWORD = DEFAULT_USERNAME\n\n\nclass Credentials:\n    def __init__(self, username, password) -> None:\n        super().__init__()\n        self.username = username\n        self.password = password\n\n\ndef timed(fn):\n    @wraps(fn)\n    def wrapper(*args, **kwargs):\n        started = perf_counter()\n        try:\n            return fn(*args, **kwargs)\n        finally:\n            print(f\"{fn.__qualname__}: {perf_counter() - started:.3f}s\")\n\n    return wrapper",
        "lineStart": 1,
        "lineEnd": 92,
        "totalLines": 92,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716205236,
      "end": 1793716205254
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/credentials.py"
}

Output

<path>/source/head/fortinet/common/features/credentials.py</path>
<type>file</type>
<content>
1: """Administrator bootstrap feature."""
2: 
3: from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction
4: from ..common import FOSCliState
5: 
6: from .base import StaticFeature
7: 
8: 
9: class CredentialsFeature(StaticFeature):
10:     """Configure the administrator, then log out and authenticate again."""
11: 
12:     def __init__(self, vm, commander):
13:         self._activate_after_admin_commit = False
14:         self._desired_credentials_activated = False
15:         self._password_change_committed = False
16:         credentials = vm.desired_credentials
17:         admin_children = ["set accprofile super_admin"]
18:         if credentials.password:
19:             admin_children.append(CommandSpec(
20:                 f"set password {credentials.password}",
21:                 session_loss=SessionLossAction.CONTINUE,
22:                 capture_output=True,
23:                 fail_on_error=True,
24:             ))
25:         elif credentials.username == "admin":
26:             admin_children.append(CommandSpec(
27:                 "unset password", session_loss=SessionLossAction.CONTINUE,
28:                 capture_output=True,
29:                 fail_on_error=True,
30:             ))
31:         super().__init__(vm, commander, "admin", [
32:             ConfigBlock("system password-policy", ["set status disable"]),
33:             ConfigBlock("system admin", [EditBlock(credentials.username, admin_children)]),
34:             CommandSequence("admin-relogin", [CommandSpec(
35:                 "exit",
36:                 session_loss=SessionLossAction.CONTINUE,
37:                 capture_output=True,
38:                 fail_on_error=True,
39:                 # A successful logout takes the session-loss path. Returning
40:                 # straight to a CLI prompt must not count as verification.
41:                 expected_completion_state=FOSCliState.PROVIDE_USERNAME,
42:             )]),
43:         ], on_complete=lambda: self._activate_desired_credentials())
44: 
45:     def on_command_dispatched(self, attempt):
46:         if attempt.spec.line == "exit":
47:             self._activate_desired_credentials()
48:         super().on_command_dispatched(attempt)
49: 
50:     def on_session_loss(self, attempt):
51:         if attempt.spec.line == "exit":
52:             # The commander resumes this block only at the authenticated CLI
53:             # prompt. Clear the logout command so it cannot be replayed.
54:             return SessionLossAction.CONTINUE
55:         if self._is_password_command(attempt.spec.line):
56:             self._activate_desired_credentials()
57:             self._activate_after_admin_commit = False
58:             return SessionLossAction.CONTINUE
59:         if self._activate_after_admin_commit and attempt.spec.line == "next":
60:             # Some releases log out during the commit instead of returning
61:             # its CLI prompt. Authenticate with the committed password.
62:             self._activate_desired_credentials()
63:             self._activate_after_admin_commit = False
64:             self._password_change_committed = True
65:             return SessionLossAction.CONTINUE
66:         if self._password_change_committed:
67:             # FortiOS may log out as the admin edit closes. The password
68:             # command and `next` have already committed the new credentials,
69:             # so replaying this block would use the previous password again.
70:             return SessionLossAction.CONTINUE
71:         return super().on_session_loss(attempt)
72: 
73:     def on_command_executed(self, command, state):
74:         line = command.spec.line
75:         if self._is_password_command(line):
76:             self._activate_after_admin_commit = True
77:         elif self._activate_after_admin_commit and line == "next":
78:             self._activate_desired_credentials()
79:             self._activate_after_admin_commit = False
80:             self._password_change_committed = True
81: 
82:     @staticmethod
83:     def _is_password_command(line):
84:         return line.startswith("set password ") or line == "unset password"
85: 
86:     def _activate_desired_credentials(self):
87:         if self._desired_credentials_activated:
88:             return
89:         self.vm.activate_desired_credentials()
90:         self._desired_credentials_activated = True

(End of file - total 90 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d136fc001eAo5MFKZCWWJQe",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d128420016vUfaFoGrZAE1p",
  "callID": "call_c7abf42a5c9e43d8813c4e8a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/credentials.py"
    },
    "output": "<path>/source/head/fortinet/common/features/credentials.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Administrator bootstrap feature.\"\"\"\n2: \n3: from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n4: from ..common import FOSCliState\n5: \n6: from .base import StaticFeature\n7: \n8: \n9: class CredentialsFeature(StaticFeature):\n10:     \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n11: \n12:     def __init__(self, vm, commander):\n13:         self._activate_after_admin_commit = False\n14:         self._desired_credentials_activated = False\n15:         self._password_change_committed = False\n16:         credentials = vm.desired_credentials\n17:         admin_children = [\"set accprofile super_admin\"]\n18:         if credentials.password:\n19:             admin_children.append(CommandSpec(\n20:                 f\"set password {credentials.password}\",\n21:                 session_loss=SessionLossAction.CONTINUE,\n22:                 capture_output=True,\n23:                 fail_on_error=True,\n24:             ))\n25:         elif credentials.username == \"admin\":\n26:             admin_children.append(CommandSpec(\n27:                 \"unset password\", session_loss=SessionLossAction.CONTINUE,\n28:                 capture_output=True,\n29:                 fail_on_error=True,\n30:             ))\n31:         super().__init__(vm, commander, \"admin\", [\n32:             ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n33:             ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n34:             CommandSequence(\"admin-relogin\", [CommandSpec(\n35:                 \"exit\",\n36:                 session_loss=SessionLossAction.CONTINUE,\n37:                 capture_output=True,\n38:                 fail_on_error=True,\n39:                 # A successful logout takes the session-loss path. Returning\n40:                 # straight to a CLI prompt must not count as verification.\n41:                 expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n42:             )]),\n43:         ], on_complete=lambda: self._activate_desired_credentials())\n44: \n45:     def on_command_dispatched(self, attempt):\n46:         if attempt.spec.line == \"exit\":\n47:             self._activate_desired_credentials()\n48:         super().on_command_dispatched(attempt)\n49: \n50:     def on_session_loss(self, attempt):\n51:         if attempt.spec.line == \"exit\":\n52:             # The commander resumes this block only at the authenticated CLI\n53:             # prompt. Clear the logout command so it cannot be replayed.\n54:             return SessionLossAction.CONTINUE\n55:         if self._is_password_command(attempt.spec.line):\n56:             self._activate_desired_credentials()\n57:             self._activate_after_admin_commit = False\n58:             return SessionLossAction.CONTINUE\n59:         if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n60:             # Some releases log out during the commit instead of returning\n61:             # its CLI prompt. Authenticate with the committed password.\n62:             self._activate_desired_credentials()\n63:             self._activate_after_admin_commit = False\n64:             self._password_change_committed = True\n65:             return SessionLossAction.CONTINUE\n66:         if self._password_change_committed:\n67:             # FortiOS may log out as the admin edit closes. The password\n68:             # command and `next` have already committed the new credentials,\n69:             # so replaying this block would use the previous password again.\n70:             return SessionLossAction.CONTINUE\n71:         return super().on_session_loss(attempt)\n72: \n73:     def on_command_executed(self, command, state):\n74:         line = command.spec.line\n75:         if self._is_password_command(line):\n76:             self._activate_after_admin_commit = True\n77:         elif self._activate_after_admin_commit and line == \"next\":\n78:             self._activate_desired_credentials()\n79:             self._activate_after_admin_commit = False\n80:             self._password_change_committed = True\n81: \n82:     @staticmethod\n83:     def _is_password_command(line):\n84:         return line.startswith(\"set password \") or line == \"unset password\"\n85: \n86:     def _activate_desired_credentials(self):\n87:         if self._desired_credentials_activated:\n88:             return\n89:         self.vm.activate_desired_credentials()\n90:         self._desired_credentials_activated = True\n\n(End of file - total 90 lines)\n</content>",
    "title": "source/head/fortinet/common/features/credentials.py",
    "metadata": {
      "preview": "\"\"\"Administrator bootstrap feature.\"\"\"\n\nfrom ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\nfrom ..common import FOSCliState\n\nfrom .base import StaticFeature\n\n\nclass CredentialsFeature(StaticFeature):\n    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n\n    def __init__(self, vm, commander):\n        self._activate_after_admin_commit = False\n        self._desired_credentials_activated = False\n        self._password_change_committed = False\n        credentials = vm.desired_credentials\n        admin_children = [\"set accprofile super_admin\"]\n        if credentials.password:\n            admin_children.append(CommandSpec(\n                f\"set password {credentials.password}\",",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/credentials.py",
        "text": "\"\"\"Administrator bootstrap feature.\"\"\"\n\nfrom ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\nfrom ..common import FOSCliState\n\nfrom .base import StaticFeature\n\n\nclass CredentialsFeature(StaticFeature):\n    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n\n    def __init__(self, vm, commander):\n        self._activate_after_admin_commit = False\n        self._desired_credentials_activated = False\n        self._password_change_committed = False\n        credentials = vm.desired_credentials\n        admin_children = [\"set accprofile super_admin\"]\n        if credentials.password:\n            admin_children.append(CommandSpec(\n                f\"set password {credentials.password}\",\n                session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n            ))\n        elif credentials.username == \"admin\":\n            admin_children.append(CommandSpec(\n                \"unset password\", session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n            ))\n        super().__init__(vm, commander, \"admin\", [\n            ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n            ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n            CommandSequence(\"admin-relogin\", [CommandSpec(\n                \"exit\",\n                session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n                # A successful logout takes the session-loss path. Returning\n                # straight to a CLI prompt must not count as verification.\n                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n            )]),\n        ], on_complete=lambda: self._activate_desired_credentials())\n\n    def on_command_dispatched(self, attempt):\n        if attempt.spec.line == \"exit\":\n            self._activate_desired_credentials()\n        super().on_command_dispatched(attempt)\n\n    def on_session_loss(self, attempt):\n        if attempt.spec.line == \"exit\":\n            # The commander resumes this block only at the authenticated CLI\n            # prompt. Clear the logout command so it cannot be replayed.\n            return SessionLossAction.CONTINUE\n        if self._is_password_command(attempt.spec.line):\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            return SessionLossAction.CONTINUE\n        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n            # Some releases log out during the commit instead of returning\n            # its CLI prompt. Authenticate with the committed password.\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            self._password_change_committed = True\n            return SessionLossAction.CONTINUE\n        if self._password_change_committed:\n            # FortiOS may log out as the admin edit closes. The password\n            # command and `next` have already committed the new credentials,\n            # so replaying this block would use the previous password again.\n            return SessionLossAction.CONTINUE\n        return super().on_session_loss(attempt)\n\n    def on_command_executed(self, command, state):\n        line = command.spec.line\n        if self._is_password_command(line):\n            self._activate_after_admin_commit = True\n        elif self._activate_after_admin_commit and line == \"next\":\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            self._password_change_committed = True\n\n    @staticmethod\n    def _is_password_command(line):\n        return line.startswith(\"set password \") or line == \"unset password\"\n\n    def _activate_desired_credentials(self):\n        if self._desired_credentials_activated:\n            return\n        self.vm.activate_desired_credentials()\n        self._desired_credentials_activated = True",
        "lineStart": 1,
        "lineEnd": 90,
        "totalLines": 90,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716205312,
      "end": 1793716205318
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/base.py"
}

Output

<path>/source/head/fortinet/common/features/base.py</path>
<type>file</type>
<content>
1: """Shared feature lifecycle primitives."""
2: 
3: 
4: class Feature:
5:     def __init__(self, vm, commander, name):
6:         self.vm = vm
7:         self.commander = commander
8:         self.name = name
9:         self._completed = False
10:         self._current_attempt = None
11: 
12:     @property
13:     def completed(self):
14:         return self._completed
15: 
16:     def mark_completed(self):
17:         self._completed = True
18: 
19:     @property
20:     def completion_message(self):
21:         return None
22: 
23:     def begin_activation(self):
24:         """Prepare this feature instance for an initial or later command stage."""
25:         self._completed = False
26:         self._current_attempt = None
27: 
28:     @property
29:     def current_attempt(self):
30:         return self._current_attempt
31: 
32:     @property
33:     def current_command(self):
34:         return self._current_attempt.spec if self._current_attempt else None
35: 
36:     @property
37:     def command_output(self):
38:         return bytes(self._current_attempt.output) if self._current_attempt else b""
39: 
40:     def activate(self):
41:         self.commander.feature_complete(self)
42: 
43:     def on_command_dispatched(self, attempt):
44:         self._current_attempt = attempt
45: 
46:     def on_output(self, output):
47:         return False
48: 
49:     def on_command_executed(self, command, state):
50:         pass
51: 
52:     def on_block_complete(self):
53:         self.commander.feature_complete(self)
54: 
55:     def on_session_loss(self, attempt):
56:         return attempt.spec.session_loss
57: 
58:     def on_context_loss(self, attempt):
59:         """Choose whether the commander may replay this interrupted block."""
60:         return attempt.spec.context_loss
61: 
62:     def reversal_blocks(self):
63:         """Return command blocks that completely reverse this feature's work."""
64:         return []
65: 
66:     def undo(self):
67:         """Return a feature stage that reverses this completed feature."""
68:         return _FeatureUndo(self.vm, self.commander, self)
69: 
70:     @property
71:     def file_path(self):
72:         """Return the optional file path watched for this feature."""
73:         return None
74: 
75:     def on_file_detected(self, path):
76:         pass
77: 
78:     def on_file_deleted(self, path):
79:         pass
80: 
81:     def on_file_modified(self, path):
82:         pass
83: 
84: 
85: class StaticFeature(Feature):
86:     """A feature whose command blocks are known when it is constructed."""
87: 
88:     def __init__(self, vm, commander, name, blocks, on_complete=None):
89:         super().__init__(vm, commander, name)
90:         self._blocks = list(blocks)
91:         self._on_complete = on_complete
92: 
93:     def activate(self):
94:         self._submit_next()
95: 
96:     def _submit_next(self):
97:         if self._blocks:
98:             self.commander.submit_block(self, self._blocks.pop(0))
99:             return
100:         if self._on_complete:
101:             self._on_complete()
102:         self.commander.feature_complete(self)
103: 
104:     def on_block_complete(self):
105:         self._submit_next()
106: 
107: 
108: class _FeatureUndo(StaticFeature):
109:     """A scheduled reversal stage created by ``Feature.undo``."""
110: 
111:     def __init__(self, vm, commander, target):
112:         super().__init__(vm, commander, f"undo-{target.name}", ())
113:         self._target = target
114: 
115:     def activate(self):
116:         if not self._target.completed:
117:             raise RuntimeError(f"Cannot undo incomplete feature {self._target.name}")
118:         self._blocks = list(self._target.reversal_blocks())
119:         super().activate()

(End of file - total 119 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d1374b001e3W3qT5y55ZgZL",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d128420016vUfaFoGrZAE1p",
  "callID": "call_bf824bfa18c34fe9aa849ec8",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/base.py"
    },
    "output": "<path>/source/head/fortinet/common/features/base.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Shared feature lifecycle primitives.\"\"\"\n2: \n3: \n4: class Feature:\n5:     def __init__(self, vm, commander, name):\n6:         self.vm = vm\n7:         self.commander = commander\n8:         self.name = name\n9:         self._completed = False\n10:         self._current_attempt = None\n11: \n12:     @property\n13:     def completed(self):\n14:         return self._completed\n15: \n16:     def mark_completed(self):\n17:         self._completed = True\n18: \n19:     @property\n20:     def completion_message(self):\n21:         return None\n22: \n23:     def begin_activation(self):\n24:         \"\"\"Prepare this feature instance for an initial or later command stage.\"\"\"\n25:         self._completed = False\n26:         self._current_attempt = None\n27: \n28:     @property\n29:     def current_attempt(self):\n30:         return self._current_attempt\n31: \n32:     @property\n33:     def current_command(self):\n34:         return self._current_attempt.spec if self._current_attempt else None\n35: \n36:     @property\n37:     def command_output(self):\n38:         return bytes(self._current_attempt.output) if self._current_attempt else b\"\"\n39: \n40:     def activate(self):\n41:         self.commander.feature_complete(self)\n42: \n43:     def on_command_dispatched(self, attempt):\n44:         self._current_attempt = attempt\n45: \n46:     def on_output(self, output):\n47:         return False\n48: \n49:     def on_command_executed(self, command, state):\n50:         pass\n51: \n52:     def on_block_complete(self):\n53:         self.commander.feature_complete(self)\n54: \n55:     def on_session_loss(self, attempt):\n56:         return attempt.spec.session_loss\n57: \n58:     def on_context_loss(self, attempt):\n59:         \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n60:         return attempt.spec.context_loss\n61: \n62:     def reversal_blocks(self):\n63:         \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n64:         return []\n65: \n66:     def undo(self):\n67:         \"\"\"Return a feature stage that reverses this completed feature.\"\"\"\n68:         return _FeatureUndo(self.vm, self.commander, self)\n69: \n70:     @property\n71:     def file_path(self):\n72:         \"\"\"Return the optional file path watched for this feature.\"\"\"\n73:         return None\n74: \n75:     def on_file_detected(self, path):\n76:         pass\n77: \n78:     def on_file_deleted(self, path):\n79:         pass\n80: \n81:     def on_file_modified(self, path):\n82:         pass\n83: \n84: \n85: class StaticFeature(Feature):\n86:     \"\"\"A feature whose command blocks are known when it is constructed.\"\"\"\n87: \n88:     def __init__(self, vm, commander, name, blocks, on_complete=None):\n89:         super().__init__(vm, commander, name)\n90:         self._blocks = list(blocks)\n91:         self._on_complete = on_complete\n92: \n93:     def activate(self):\n94:         self._submit_next()\n95: \n96:     def _submit_next(self):\n97:         if self._blocks:\n98:             self.commander.submit_block(self, self._blocks.pop(0))\n99:             return\n100:         if self._on_complete:\n101:             self._on_complete()\n102:         self.commander.feature_complete(self)\n103: \n104:     def on_block_complete(self):\n105:         self._submit_next()\n106: \n107: \n108: class _FeatureUndo(StaticFeature):\n109:     \"\"\"A scheduled reversal stage created by ``Feature.undo``.\"\"\"\n110: \n111:     def __init__(self, vm, commander, target):\n112:         super().__init__(vm, commander, f\"undo-{target.name}\", ())\n113:         self._target = target\n114: \n115:     def activate(self):\n116:         if not self._target.completed:\n117:             raise RuntimeError(f\"Cannot undo incomplete feature {self._target.name}\")\n118:         self._blocks = list(self._target.reversal_blocks())\n119:         super().activate()\n\n(End of file - total 119 lines)\n</content>",
    "title": "source/head/fortinet/common/features/base.py",
    "metadata": {
      "preview": "\"\"\"Shared feature lifecycle primitives.\"\"\"\n\n\nclass Feature:\n    def __init__(self, vm, commander, name):\n        self.vm = vm\n        self.commander = commander\n        self.name = name\n        self._completed = False\n        self._current_attempt = None\n\n    @property\n    def completed(self):\n        return self._completed\n\n    def mark_completed(self):\n        self._completed = True\n\n    @property\n    def completion_message(self):",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/base.py",
        "text": "\"\"\"Shared feature lifecycle primitives.\"\"\"\n\n\nclass Feature:\n    def __init__(self, vm, commander, name):\n        self.vm = vm\n        self.commander = commander\n        self.name = name\n        self._completed = False\n        self._current_attempt = None\n\n    @property\n    def completed(self):\n        return self._completed\n\n    def mark_completed(self):\n        self._completed = True\n\n    @property\n    def completion_message(self):\n        return None\n\n    def begin_activation(self):\n        \"\"\"Prepare this feature instance for an initial or later command stage.\"\"\"\n        self._completed = False\n        self._current_attempt = None\n\n    @property\n    def current_attempt(self):\n        return self._current_attempt\n\n    @property\n    def current_command(self):\n        return self._current_attempt.spec if self._current_attempt else None\n\n    @property\n    def command_output(self):\n        return bytes(self._current_attempt.output) if self._current_attempt else b\"\"\n\n    def activate(self):\n        self.commander.feature_complete(self)\n\n    def on_command_dispatched(self, attempt):\n        self._current_attempt = attempt\n\n    def on_output(self, output):\n        return False\n\n    def on_command_executed(self, command, state):\n        pass\n\n    def on_block_complete(self):\n        self.commander.feature_complete(self)\n\n    def on_session_loss(self, attempt):\n        return attempt.spec.session_loss\n\n    def on_context_loss(self, attempt):\n        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n        return attempt.spec.context_loss\n\n    def reversal_blocks(self):\n        \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n        return []\n\n    def undo(self):\n        \"\"\"Return a feature stage that reverses this completed feature.\"\"\"\n        return _FeatureUndo(self.vm, self.commander, self)\n\n    @property\n    def file_path(self):\n        \"\"\"Return the optional file path watched for this feature.\"\"\"\n        return None\n\n    def on_file_detected(self, path):\n        pass\n\n    def on_file_deleted(self, path):\n        pass\n\n    def on_file_modified(self, path):\n        pass\n\n\nclass StaticFeature(Feature):\n    \"\"\"A feature whose command blocks are known when it is constructed.\"\"\"\n\n    def __init__(self, vm, commander, name, blocks, on_complete=None):\n        super().__init__(vm, commander, name)\n        self._blocks = list(blocks)\n        self._on_complete = on_complete\n\n    def activate(self):\n        self._submit_next()\n\n    def _submit_next(self):\n        if self._blocks:\n            self.commander.submit_block(self, self._blocks.pop(0))\n            return\n        if self._on_complete:\n            self._on_complete()\n        self.commander.feature_complete(self)\n\n    def on_block_complete(self):\n        self._submit_next()\n\n\nclass _FeatureUndo(StaticFeature):\n    \"\"\"A scheduled reversal stage created by ``Feature.undo``.\"\"\"\n\n    def __init__(self, vm, commander, target):\n        super().__init__(vm, commander, f\"undo-{target.name}\", ())\n        self._target = target\n\n    def activate(self):\n        if not self._target.completed:\n            raise RuntimeError(f\"Cannot undo incomplete feature {self._target.name}\")\n        self._blocks = list(self._target.reversal_blocks())\n        super().activate()",
        "lineStart": 1,
        "lineEnd": 119,
        "totalLines": 119,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716205391,
      "end": 1793716205397
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d13756001bxNchZiImKTc1k",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d128420016vUfaFoGrZAE1p",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 51231,
    "input": 12904,
    "output": 89,
    "reasoning": 286,
    "cache": {
      "read": 37952,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d128420016vUfaFoGrZAE1p",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716201538,
    "completed": 1793716205401
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 51231,
    "input": 12904,
    "output": 89,
    "reasoning": 286,
    "cache": {
      "read": 37952,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 6
step-start
{
  "type": "step-start",
  "id": "prt_1a1d14b97001Kb3CiUVsRqIsCx",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1375c001FIizK8w9R74JaS"
}
Reasoning
Now the big ones: fos_commander.py (687 lines head) and terminal.py, fos_cli_driver.py, startup_config.py, launch.py.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_commander.py"
}

Output

<path>/source/head/fortinet/common/fos_commander.py</path>
<type>file</type>
<content>
1: """Event-driven command scheduler for the FortiOS CLI."""
2: 
3: import datetime
4: import re
5: from collections import deque
6: from contextlib import ExitStack
7: from dataclasses import dataclass
8: 
9: from .cli_commands import (
10:     CleanupAction,
11:     CommandAttempt,
12:     CommandSequence,
13:     CommandSpec,
14:     ConfigBlock,
15:     ContextLossAction,
16:     SessionLossAction,
17:     flatten_commands,
18: )
19: from .terminal import Data
20: from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL
21: 
22: DISPATCHABLE_COMPLETION_STATES = {
23:     FOSCliState.CMD_PROMPT,
24:     FOSCliState.CONFIRMATION,
25:     FOSCliState.MULTILINE_PROMPT,
26: }
27: COMMAND_FAILURE_PATTERN = re.compile(
28:     rb"(?mi)^\s*Command fail\.\s*Return code\s+(-?\d+)"
29: )
30: CLI_PROMPT_CONTEXT_PATTERN = re.compile(
31:     rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX
32:     + rb"(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$"
33: )
34: 
35: 
36: @dataclass
37: class _StandardOutputContext:
38:     feature: object
39:     callback: object
40:     phase: str = "inspect"
41:     restore: bool = False
42: 
43: 
44: class FOSCommander:
45:     MAX_COMMAND_RECOVERY_RETRIES = 1
46:     _CONSOLE_OUTPUT_PATTERN = re.compile(rb"(?mi)^\s*set output (more|standard)\s*\r?$")
47:     _CONSOLE_INSPECT_LINE = "show full-configuration system console"
48:     _CONSOLE_STANDARD_LINE = "set output standard"
49: 
50:     def __init__(self, terminal, logger, continue_on_error=False):
51:         self.terminal = terminal
52:         self.logger = logger
53:         self._features = deque()
54:         self._active_feature = None
55:         self._active_commands = ()
56:         self._pending = deque()
57:         self._inflight = None
58:         self._attempt_number = 0
59:         self._session_epoch = 0
60:         self._recovering = False
61:         self._cleanup = deque()
62:         self._cleanup_actions = {}
63:         self._in_cleanup = False
64:         self._standard_output_context = None
65:         self._suppression = ExitStack()
66:         self._ready = False
67:         self._startup_complete = False
68:         self._feature_errors = []
69:         self._authenticated_once = False
70:         self._completed_messages = deque()
71:         self._start_time = datetime.datetime.now()
72:         self._continue_on_error = continue_on_error
73:         self._pending_feature_error = None
74:         self._current_state = None
75:         self._callback_failed = False
76:         self._prompt_context = None
77:         self._block_prompt_context = None
78:         self._recovery_retries = {}
79:         self._cleanup_retries = {}
80:         self._replay_context_target = None
81:         self._context_reset_attempted = False
82:         self._in_context_reset = False
83: 
84:     def _call_feature(self, callback, *args):
85:         """Run a feature callback and apply best-effort policy at this boundary."""
86:         try:
87:             return callback(*args)
88:         except Exception as error:
89:             self._handle_work_error(error, from_callback=True)
90:             return None
91: 
92:     def _handle_work_error(self, error, *, from_callback=False):
93:         """Apply the configured failure policy after feature/recovery decisions."""
94:         if not self._continue_on_error:
95:             raise error
96:         if from_callback:
97:             self.logger.exception("Bootstrap feature callback failed")
98:         else:
99:             self.logger.error("Bootstrap work failed: %s", error, exc_info=error)
100:         self._pending_feature_error = error
101:         self._callback_failed = True
102: 
103:     def _recover_feature_error(self, *, at_idle_prompt=False):
104:         error = self._pending_feature_error
105:         if error is None or (
106:             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
107:         ):
108:             return False
109:         failed_work = self.continue_after_error(error, at_command_prompt=True)
110:         if failed_work is None:
111:             return False
112:         self._pending_feature_error = None
113:         self.logger.error(
114:             "Bootstrap work %s failed; continuing with remaining features "
115:             "because FOS_EXIT_ON_BOOTSTRAP_ERROR=false",
116:             failed_work,
117:         )
118:         self._dispatch_next()
119:         return True
120: 
121:     @property
122:     def ready(self):
123:         return self._ready
124: 
125:     @property
126:     def busy(self):
127:         return self._inflight is not None or bool(self._pending) or bool(self._cleanup)
128: 
129:     @property
130:     def startup_complete(self):
131:         """Whether the initial feature queue has drained, with or without errors."""
132:         return self._startup_complete
133: 
134:     @property
135:     def feature_errors(self):
136:         """Bootstrap feature errors recorded while best-effort mode is active."""
137:         return tuple(self._feature_errors)
138: 
139:     def continue_after_error(self, error, at_command_prompt):
140:         """Skip failed work only when the CLI is back at a usable prompt.
141: 
142:         A login rejection after the driver's credential recovery attempts, or
143:         an error during an interactive prompt, cannot be recovered by sending
144:         the next feature's commands, so automatic bootstrap must stop.
145:         """
146:         if not at_command_prompt or self._ready:
147:             return None
148:         if self._active_feature is None and not self._in_cleanup:
149:             return None
150: 
151:         if self._active_feature is not None:
152:             failed_name = self._active_feature.name
153:             self._pending.clear()
154:             self._active_commands = ()
155:             self._inflight = None
156:             self._suppression.close()
157:             self._suppression = ExitStack()
158:             self._finish_standard_output_context(self._active_feature)
159:             self._schedule_feature_cleanup(self._active_feature, "interruption")
160:             self._active_feature = None
161:         else:
162:             failed_name = "cleanup"
163:             self._inflight = None
164:             self._suppression.close()
165:             self._suppression = ExitStack()
166: 
167:         self._in_cleanup = False
168:         self._replay_context_target = None
169:         self._in_context_reset = False
170:         self._cleanup_retries.clear()
171:         self._feature_errors.append((failed_name, str(error)))
172:         return failed_name
173: 
174:     def record_feature_error(self, name, error):
175:         """Record a recoverable bootstrap problem without stopping the queue."""
176:         self._feature_errors.append((name, str(error)))
177:         self.logger.info("Using recovery for %s: %s", name, error)
178: 
179:     def resolve_feature_error(self, name, resolution):
180:         """Clear a recoverable feature error after its condition is resolved."""
181:         remaining = [
182:             (feature_name, error)
183:             for feature_name, error in self._feature_errors
184:             if feature_name != name
185:         ]
186:         resolved_count = len(self._feature_errors) - len(remaining)
187:         if resolved_count:
188:             self._feature_errors = remaining
189:             self.logger.info(
190:                 "Resolved %s bootstrap recovery after %s",
191:                 name,
192:                 resolution,
193:             )
194: 
195:     def start(self, features):
196:         self._features.extend(features)
197: 
198:     def tick(self):
199:         if self._pending_feature_error is not None:
200:             return
201:         if self._active_feature and hasattr(self._active_feature, "tick"):
202:             self._call_feature(self._active_feature.tick)
203: 
204:     def submit_block(self, feature, block):
205:         if feature is not self._active_feature:
206:             raise RuntimeError("Inactive feature attempted to submit commands")
207:         if self.busy:
208:             raise RuntimeError("Cannot replace an active command block")
209:         commands = tuple(flatten_commands(block))
210:         self._active_commands = commands
211:         self._pending = deque(commands)
212:         self._block_prompt_context = self._prompt_context
213:         self._recovery_retries = {}
214:         self._replay_context_target = None
215:         self._context_reset_attempted = False
216: 
217:     def feature_complete(self, feature):
218:         if feature is not self._active_feature:
219:             return
220:         if self.busy:
221:             raise RuntimeError("Feature completed while commands are still pending")
222:         feature.mark_completed()
223:         if feature.completion_message:
224:             self._completed_messages.append(feature.completion_message)
225:         self._finish_standard_output_context(feature)
226:         self._schedule_feature_cleanup(feature, "completion")
227:         self._active_feature = None
228:         self._active_commands = ()
229:         if not self._cleanup:
230:             self._activate_next_feature()
231: 
232:     def register_cleanup(self, feature, action):
233:         if not isinstance(action, CleanupAction):
234:             raise TypeError("cleanup must be a CleanupAction")
235:         self._cleanup_actions.setdefault(feature, []).append(action)
236: 
237:     def with_standard_output(self, feature, callback):
238:         """Run a feature callback after standard console output is available."""
239:         if feature is not self._active_feature:
240:             raise RuntimeError("Inactive feature requested standard console output")
241:         if self.busy or self._standard_output_context:
242:             raise RuntimeError("Cannot start a standard console output context while busy")
243:         self._standard_output_context = _StandardOutputContext(feature, callback)
244:         self.submit_block(feature, CommandSequence("console-output-inspect", [
245:             CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),
246:         ]))
247: 
248:     def _schedule_feature_cleanup(self, feature, trigger):
249:         actions = self._cleanup_actions.pop(feature, [])
250:         for action in actions:
251:             if (trigger == "completion" and action.on_completion) or (
252:                 trigger == "interruption" and action.on_interruption
253:             ):
254:                 self.logger.debug(f"Scheduling cleanup {action.name} after {trigger}")
255:                 self._cleanup.extend(action.block.flatten())
256: 
257:     def on_output(self, output):
258:         if not isinstance(output, Data):
259:             raise TypeError("commander output must be terminal.Data")
260:         if not output:
261:             return output
262:         if self._inflight:
263:             if self._call_feature(self._inflight.on_output, output):
264:                 return output
265:             if self._active_feature and self._call_feature(self._active_feature.on_output, output):
266:                 return output
267:         self._inspect_output(output)
268:         return output
269: 
270:     def on_state(self, state, output):
271:         """Called by the driver for every recognized serial state."""
272:         self._current_state = state
273:         self._callback_failed = False
274:         if state == FOSCliState.CMD_PROMPT:
275:             context = self._extract_prompt_context(output)
276:             if context is not None:
277:                 self._prompt_context = context
278:             # Some releases return directly to a usable prompt after login,
279:             # without a Welcome banner. The prompt also ends session recovery.
280:             self._authenticated_once = True
281:             self._recovering = False
282:         if self._pending_feature_error is not None:
283:             if state == FOSCliState.CMD_PROMPT:
284:                 self._recover_feature_error()
285:             elif state == FOSCliState.SESSION_LOST:
286:                 self._session_epoch += 1
287:                 self._recovering = True
288:             elif state == FOSCliState.CREDENTIAL_ACCEPTED:
289:                 self._authenticated_once = True
290:                 self._recovering = False
291:             return
292:         self.on_output(output)
293:         if self._callback_failed:
294:             if state == FOSCliState.CMD_PROMPT:
295:                 self._recover_feature_error()
296:             return
297:         if self._pending_feature_error is not None:
298:             if state == FOSCliState.CMD_PROMPT:
299:                 self._recover_feature_error()
300:             return
301: 
302:         if state == FOSCliState.SESSION_LOST:
303:             self._handle_session_loss()
304:             return
305:         if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:
306:             # Password updates can return to login without the explicit
307:             # SESSION_LOST banner. Requeue the active command block so it is
308:             # applied after the driver restores an accepted login.
309:             self._handle_session_loss()
310:             return
311:         if state == FOSCliState.CREDENTIAL_ACCEPTED:
312:             self._authenticated_once = True
313:             self._recovering = False
314:             return
315:         if self._inflight and state in (
316:             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
317:         ):
318:             self._complete_inflight(state)
319:             return
320: 
321:         if state == FOSCliState.CMD_PROMPT and not self._recovering:
322:             self._dispatch_next()
323:         if self._callback_failed and state == FOSCliState.CMD_PROMPT:
324:             self._recover_feature_error()
325: 
326:     def on_prompt_echo(self, output):
327:         """Handle a prompt line that had trailing text after the prompt token."""
328:         if self.on_output(output).discarded:
329:             return
330:         self.logger.debug("Prompt had unexpected trailing output; requesting a clean prompt")
331:         self.terminal.write(b"\r")
332: 
333:     def _inspect_output(self, output):
334:         if self._recovering:
335:             output.discard()
336: 
337:     def on_idle_prompt(self):
338:         """Recover errors or dispatch work while idle at a known prompt."""
339:         if self._inflight or self._recovering:
340:             return
341:         if self._pending_feature_error is not None:
342:             # The driver calls this after a read timeout at a known CLI prompt.
343:             # on_state has since recorded TN_TIMEOUT, so recover explicitly.
344:             self._recover_feature_error(at_idle_prompt=True)
345:             return
346:         if self._pending or self._cleanup or self._active_feature is None:
347:             self._dispatch_next()
348: 
349:     def _activate_next_feature(self):
350:         if self._ready or self._active_feature or self._recovering:
351:             return
352:         if not self._features:
353:             if self._cleanup:
354:                 return
355:             self._ready = True
356:             self.terminal.close()
357:             if not self._startup_complete:
358:                 self._startup_complete = True
359:                 elapsed = datetime.datetime.now() - self._start_time
360:                 if self._feature_errors:
361:                     failed = ", ".join(name for name, _error in self._feature_errors)
362:                     self.logger.error(
363:                         "Bootstrap reached the end with %d feature error(s) in %s; "
364:                         "failed work: %s",
365:                         len(self._feature_errors),
366:                         elapsed,
367:                         failed,
368:                     )
369:                 else:
370:                     self.logger.info(f"Startup complete in {elapsed}")
371:             else:
372:                 while self._completed_messages:
373:                     self.logger.info(self._completed_messages.popleft())
374:             return
375:         self._active_feature = self._features.popleft()
376:         self.logger.info(f"Activating feature {self._active_feature.name}")
377:         self._call_feature(self._active_feature.begin_activation)
378:         if self._pending_feature_error is None:
379:             self._call_feature(self._active_feature.activate)
380: 
381:     def _dispatch_next(self):
382:         if self._inflight or self._recovering or self._pending_feature_error is not None:
383:             return
384:         if not self._restore_replay_context():
385:             return
386:         if not self._cleanup and self._active_feature is None:
387:             self._activate_next_feature()
388:             if self._active_feature is None:
389:                 return
390:         if self._cleanup:
391:             spec = self._cleanup.popleft()
392:             self._in_cleanup = True
393:             block_index = None
394:         elif not self._pending:
395:             self._call_feature(self._active_feature.on_block_complete)
396:             return
397:         else:
398:             spec = self._pending.popleft()
399:             self._in_cleanup = False
400:             block_index = len(self._active_commands) - len(self._pending) - 1
401:         self._dispatch_command(spec, block_index)
402: 
403:     def _dispatch_command(self, spec, block_index=None):
404:         self._attempt_number += 1
405:         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)
406:         self._inflight.prompt_context_before = self._prompt_context
407:         self._inflight.block_index = block_index
408:         self._inflight.retry_count = (
409:             self._cleanup_retries.get(id(spec), 0)
410:             if self._in_cleanup else self._recovery_retries.get(block_index, 0)
411:         )
412:         if self._active_feature and not self._in_context_reset:
413:             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)
414:             if self._pending_feature_error is not None:
415:                 return
416:         if spec.suppress_output:
417:             self._suppression.enter_context(self.terminal.suppress_output())
418:         self.logger.log(
419:             TRACE_LEVEL,
420:             f"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/"
421:             f"{spec.line!r}"
422:         )
423:         self.terminal.write(f"{spec.line}\r")
424: 
425:     def _complete_inflight(self, state):
426:         attempt = self._inflight
427:         self._inflight = None
428:         self._suppression.close()
429:         self._suppression = ExitStack()
430:         attempt.prompt_context_after = self._prompt_context
431:         if self._in_context_reset:
432:             self._in_context_reset = False
433:             self._dispatch_next()
434:             return
435:         if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
436:             self._handle_context_loss(attempt)
437:             if self._pending_feature_error is not None:
438:                 self._recover_feature_error()
439:             else:
440:                 self._dispatch_next()
441:             return
442:         try:
443:             self._validate_completion(attempt, state)
444:         except RuntimeError as error:
445:             if state != FOSCliState.CMD_PROMPT:
446:                 # An interactive prompt cannot safely advance to another feature.
447:                 raise
448:             self._handle_work_error(error)
449:             if self._pending_feature_error is not None:
450:                 self._recover_feature_error()
451:             return
452:         if self._in_cleanup:
453:             self._cleanup_retries.pop(id(attempt.spec), None)
454:             self._in_cleanup = False
455:             self._dispatch_next()
456:             return
457:         if self._is_standard_output_command(attempt.spec):
458:             self._complete_standard_output_command(attempt)
459:             if self._pending_feature_error is not None:
460:                 return
461:             if not self._recovering:
462:                 self._dispatch_next()
463:             return
464:         completed_feature = self._active_feature
465:         self._call_feature(completed_feature.on_command_executed, attempt, state)
466:         if self._pending_feature_error is not None:
467:             return
468:         # The callback may have installed another block (confirmation/query path).
469:         if not self.busy and self._active_feature is completed_feature:
470:             self._call_feature(completed_feature.on_block_complete)
471:         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:
472:             self._dispatch_next()
473: 
474:     @staticmethod
475:     def _validate_completion(attempt, state):
476:         if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (
477:             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))
478:         ):
479:             raise RuntimeError(
480:                 f"FortiOS command {attempt.spec.line!r} failed "
481:                 f"(return code {failure.group(1).decode()})"
482:             )
483:         expected = attempt.spec.expected_completion_state
484:         if expected is not None and state != expected:
485:             raise RuntimeError(
486:                 "CLI command completed at unexpected prompt: "
487:                 f"expected {expected.name}, received {state.name}"
488:             )
489: 
490:     def _prompt_context_changed(self, attempt):
491:         before = attempt.prompt_context_before
492:         after = attempt.prompt_context_after
493:         return (
494:             before is not None
495:             and after is not None
496:             and before != after
497:             and not self._command_may_change_context(attempt.spec)
498:         )
499: 
500:     def _handle_context_loss(self, attempt):
501:         reason = (
502:             "CLI context changed from "
503:             f"{self._format_prompt_context(attempt.prompt_context_before)} to "
504:             f"{self._format_prompt_context(attempt.prompt_context_after)}"
505:         )
506:         if self._in_cleanup:
507:             self._handle_work_error(RuntimeError(
508:                 f"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay"
509:             ))
510:             return
511:         action = self._call_feature(self._active_feature.on_context_loss, attempt)
512:         if self._pending_feature_error is not None:
513:             return
514:         if action == ContextLossAction.RESTART_BLOCK:
515:             self._restart_active_block(attempt, reason)
516:         elif action == ContextLossAction.FAIL:
517:             self._handle_work_error(RuntimeError(
518:                 f"{reason} during {attempt.spec.line!r}; feature declined replay"
519:             ))
520:         else:
521:             self._handle_work_error(ValueError(f"Unsupported context-loss action: {action!r}"))
522: 
523:     def _restore_replay_context(self):
524:         """Unwind a surviving partial scope once before replaying its openers."""
525:         target = self._replay_context_target
526:         if target is None:
527:             return True
528:         if self._prompt_context == target:
529:             self._replay_context_target = None
530:             return True
531:         if self._context_reset_attempted:
532:             self._handle_work_error(RuntimeError(
533:                 "Unable to restore CLI context before replay: expected "
534:                 f"{self._format_prompt_context(target)}, received "
535:                 f"{self._format_prompt_context(self._prompt_context or ())}"
536:             ))
537:             if self._pending_feature_error is not None:
538:                 self._recover_feature_error()
539:             return False
540:         self._context_reset_attempted = True
541:         self._in_context_reset = True
542:         self._dispatch_command(CommandSpec("abort", suppress_output=True))
543:         return False
544: 
545:     @staticmethod
546:     def _command_may_change_context(spec):
547:         if spec.continuation:
548:             return False
549:         command = spec.line.strip().lower()
550:         return (
551:             command.startswith(("config ", "edit "))
552:             or command in {"next", "end", "abort", "exit", "quit"}
553:             or command == "set vdom-mode multi-vdom"
554:         )
555: 
556:     @staticmethod
557:     def _extract_prompt_context(output):
558:         data = bytes(output)
559:         matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))
560:         if not matches:
561:             return None
562:         return tuple(
563:             item.decode(errors="replace")
564:             for item in re.findall(rb"\(([^)]*)\)", matches[-1].group("context"))
565:         )
566: 
567:     @staticmethod
568:     def _format_prompt_context(context):
569:         return " ".join(f"({item})" for item in context) or "<top-level>"
570: 
571:     def _is_standard_output_command(self, spec):
572:         context = self._standard_output_context
573:         return context is not None and (
574:             spec.line == self._CONSOLE_INSPECT_LINE
575:             or (context.phase == "set-standard" and not self._pending)
576:         )
577: 
578:     def _complete_standard_output_command(self, attempt):
579:         context = self._standard_output_context
580:         if attempt.spec.line == self._CONSOLE_INSPECT_LINE:
581:             match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))
582:             if not match or match.group(1) == b"standard":
583:                 if not match:
584:                     self.logger.warning("Could not determine console output mode; assuming standard output")
585:                 self._start_standard_output_callback(context)
586:                 return
587:             context.phase = "set-standard"
588:             self.submit_block(context.feature, ConfigBlock("system console", [
589:                 self._CONSOLE_STANDARD_LINE,
590:             ]))
591:             return
592:         if context.phase == "set-standard":
593:             context.restore = True
594:             self._start_standard_output_callback(context)
595: 
596:     def _start_standard_output_callback(self, context):
597:         context.phase = "active"
598:         self._call_feature(context.callback)
599: 
600:     def _finish_standard_output_context(self, feature):
601:         context = self._standard_output_context
602:         if context is None or context.feature is not feature:
603:             return
604:         self._standard_output_context = None
605:         if context.restore:
606:             self._cleanup.extend(ConfigBlock("system console", [
607:                 "set output more",
608:             ]).flatten())
609: 
610:     def _handle_session_loss(self):
611:         self._session_epoch += 1
612:         self._recovering = True
613:         if not self._inflight:
614:             return
615:         attempt = self._inflight
616:         self._inflight = None
617:         self._suppression.close()
618:         self._suppression = ExitStack()
619:         if self._in_context_reset:
620:             # Login may itself restore the target scope. The pending replay
621:             # stays bounded by the original command's recovery allowance.
622:             self._in_context_reset = False
623:             return
624:         if self._in_cleanup:
625:             retries = self._cleanup_retries.get(id(attempt.spec), 0)
626:             if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
627:                 self._handle_work_error(RuntimeError(
628:                     f"Session lost repeatedly during cleanup {attempt.spec.line!r}; "
629:                     "retry limit reached"
630:                 ))
631:                 return
632:             self._cleanup_retries[id(attempt.spec)] = retries + 1
633:             self._cleanup.appendleft(attempt.spec)
634:             self._in_cleanup = False
635:             return
636:         self._schedule_feature_cleanup(self._active_feature, "interruption")
637:         action = self._call_feature(
638:             self._active_feature.on_session_loss,
639:             attempt,
640:         )
641:         if self._pending_feature_error is not None:
642:             return
643:         self.logger.info(
644:             f"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}"
645:         )
646:         action_handlers = {
647:             SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(
648:                 attempt, "session lost"
649:             ),
650:             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),
651:             SessionLossAction.CONTINUE: lambda: self._pending.clear(),
652:             SessionLossAction.FAIL: lambda: self._handle_work_error(
653:                 RuntimeError(f"Session lost during {attempt.spec.line!r}")
654:             ),
655:             SessionLossAction.VALIDATE: lambda: self._pending.clear(),
656:         }
657:         action_handlers[action]()
658: 
659:     def _restart_active_block(self, attempt, reason):
660:         retries = self._recovery_retries.get(attempt.block_index, 0)
661:         if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
662:             self._handle_work_error(RuntimeError(
663:                 f"{reason} repeatedly during {attempt.spec.line!r}; "
664:                 f"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})"
665:             ))
666:             return
667:         self._recovery_retries[attempt.block_index] = retries + 1
668:         self._pending = deque(self._active_commands)
669:         self._replay_context_target = self._block_prompt_context
670:         self._context_reset_attempted = False
671:         self.logger.warning(
672:             "%s during %s/%r; replaying block (command recovery %d/%d)",
673:             reason, self._active_feature.name, attempt.spec.line,
674:             retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,
675:         )
676: 
677:     def enqueue_runtime_feature(self, feature):
678:         return self.enqueue_runtime_features([feature])
679: 
680:     def enqueue_runtime_features(self, features):
681:         if not self._ready or self.busy:
682:             return False
683:         self._ready = False
684:         self._completed_messages.clear()
685:         for feature in reversed(features):
686:             self._features.appendleft(feature)
687:         return True

(End of file - total 687 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d14cd5001Gblp9t9FRuivFA",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1375c001FIizK8w9R74JaS",
  "callID": "call_8110449e30ea46b3a1831f43",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_commander.py"
    },
    "output": "<path>/source/head/fortinet/common/fos_commander.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n2: \n3: import datetime\n4: import re\n5: from collections import deque\n6: from contextlib import ExitStack\n7: from dataclasses import dataclass\n8: \n9: from .cli_commands import (\n10:     CleanupAction,\n11:     CommandAttempt,\n12:     CommandSequence,\n13:     CommandSpec,\n14:     ConfigBlock,\n15:     ContextLossAction,\n16:     SessionLossAction,\n17:     flatten_commands,\n18: )\n19: from .terminal import Data\n20: from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n21: \n22: DISPATCHABLE_COMPLETION_STATES = {\n23:     FOSCliState.CMD_PROMPT,\n24:     FOSCliState.CONFIRMATION,\n25:     FOSCliState.MULTILINE_PROMPT,\n26: }\n27: COMMAND_FAILURE_PATTERN = re.compile(\n28:     rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n29: )\n30: CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n31:     rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n32:     + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n33: )\n34: \n35: \n36: @dataclass\n37: class _StandardOutputContext:\n38:     feature: object\n39:     callback: object\n40:     phase: str = \"inspect\"\n41:     restore: bool = False\n42: \n43: \n44: class FOSCommander:\n45:     MAX_COMMAND_RECOVERY_RETRIES = 1\n46:     _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n47:     _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n48:     _CONSOLE_STANDARD_LINE = \"set output standard\"\n49: \n50:     def __init__(self, terminal, logger, continue_on_error=False):\n51:         self.terminal = terminal\n52:         self.logger = logger\n53:         self._features = deque()\n54:         self._active_feature = None\n55:         self._active_commands = ()\n56:         self._pending = deque()\n57:         self._inflight = None\n58:         self._attempt_number = 0\n59:         self._session_epoch = 0\n60:         self._recovering = False\n61:         self._cleanup = deque()\n62:         self._cleanup_actions = {}\n63:         self._in_cleanup = False\n64:         self._standard_output_context = None\n65:         self._suppression = ExitStack()\n66:         self._ready = False\n67:         self._startup_complete = False\n68:         self._feature_errors = []\n69:         self._authenticated_once = False\n70:         self._completed_messages = deque()\n71:         self._start_time = datetime.datetime.now()\n72:         self._continue_on_error = continue_on_error\n73:         self._pending_feature_error = None\n74:         self._current_state = None\n75:         self._callback_failed = False\n76:         self._prompt_context = None\n77:         self._block_prompt_context = None\n78:         self._recovery_retries = {}\n79:         self._cleanup_retries = {}\n80:         self._replay_context_target = None\n81:         self._context_reset_attempted = False\n82:         self._in_context_reset = False\n83: \n84:     def _call_feature(self, callback, *args):\n85:         \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n86:         try:\n87:             return callback(*args)\n88:         except Exception as error:\n89:             self._handle_work_error(error, from_callback=True)\n90:             return None\n91: \n92:     def _handle_work_error(self, error, *, from_callback=False):\n93:         \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n94:         if not self._continue_on_error:\n95:             raise error\n96:         if from_callback:\n97:             self.logger.exception(\"Bootstrap feature callback failed\")\n98:         else:\n99:             self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n100:         self._pending_feature_error = error\n101:         self._callback_failed = True\n102: \n103:     def _recover_feature_error(self, *, at_idle_prompt=False):\n104:         error = self._pending_feature_error\n105:         if error is None or (\n106:             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n107:         ):\n108:             return False\n109:         failed_work = self.continue_after_error(error, at_command_prompt=True)\n110:         if failed_work is None:\n111:             return False\n112:         self._pending_feature_error = None\n113:         self.logger.error(\n114:             \"Bootstrap work %s failed; continuing with remaining features \"\n115:             \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n116:             failed_work,\n117:         )\n118:         self._dispatch_next()\n119:         return True\n120: \n121:     @property\n122:     def ready(self):\n123:         return self._ready\n124: \n125:     @property\n126:     def busy(self):\n127:         return self._inflight is not None or bool(self._pending) or bool(self._cleanup)\n128: \n129:     @property\n130:     def startup_complete(self):\n131:         \"\"\"Whether the initial feature queue has drained, with or without errors.\"\"\"\n132:         return self._startup_complete\n133: \n134:     @property\n135:     def feature_errors(self):\n136:         \"\"\"Bootstrap feature errors recorded while best-effort mode is active.\"\"\"\n137:         return tuple(self._feature_errors)\n138: \n139:     def continue_after_error(self, error, at_command_prompt):\n140:         \"\"\"Skip failed work only when the CLI is back at a usable prompt.\n141: \n142:         A login rejection after the driver's credential recovery attempts, or\n143:         an error during an interactive prompt, cannot be recovered by sending\n144:         the next feature's commands, so automatic bootstrap must stop.\n145:         \"\"\"\n146:         if not at_command_prompt or self._ready:\n147:             return None\n148:         if self._active_feature is None and not self._in_cleanup:\n149:             return None\n150: \n151:         if self._active_feature is not None:\n152:             failed_name = self._active_feature.name\n153:             self._pending.clear()\n154:             self._active_commands = ()\n155:             self._inflight = None\n156:             self._suppression.close()\n157:             self._suppression = ExitStack()\n158:             self._finish_standard_output_context(self._active_feature)\n159:             self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n160:             self._active_feature = None\n161:         else:\n162:             failed_name = \"cleanup\"\n163:             self._inflight = None\n164:             self._suppression.close()\n165:             self._suppression = ExitStack()\n166: \n167:         self._in_cleanup = False\n168:         self._replay_context_target = None\n169:         self._in_context_reset = False\n170:         self._cleanup_retries.clear()\n171:         self._feature_errors.append((failed_name, str(error)))\n172:         return failed_name\n173: \n174:     def record_feature_error(self, name, error):\n175:         \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n176:         self._feature_errors.append((name, str(error)))\n177:         self.logger.info(\"Using recovery for %s: %s\", name, error)\n178: \n179:     def resolve_feature_error(self, name, resolution):\n180:         \"\"\"Clear a recoverable feature error after its condition is resolved.\"\"\"\n181:         remaining = [\n182:             (feature_name, error)\n183:             for feature_name, error in self._feature_errors\n184:             if feature_name != name\n185:         ]\n186:         resolved_count = len(self._feature_errors) - len(remaining)\n187:         if resolved_count:\n188:             self._feature_errors = remaining\n189:             self.logger.info(\n190:                 \"Resolved %s bootstrap recovery after %s\",\n191:                 name,\n192:                 resolution,\n193:             )\n194: \n195:     def start(self, features):\n196:         self._features.extend(features)\n197: \n198:     def tick(self):\n199:         if self._pending_feature_error is not None:\n200:             return\n201:         if self._active_feature and hasattr(self._active_feature, \"tick\"):\n202:             self._call_feature(self._active_feature.tick)\n203: \n204:     def submit_block(self, feature, block):\n205:         if feature is not self._active_feature:\n206:             raise RuntimeError(\"Inactive feature attempted to submit commands\")\n207:         if self.busy:\n208:             raise RuntimeError(\"Cannot replace an active command block\")\n209:         commands = tuple(flatten_commands(block))\n210:         self._active_commands = commands\n211:         self._pending = deque(commands)\n212:         self._block_prompt_context = self._prompt_context\n213:         self._recovery_retries = {}\n214:         self._replay_context_target = None\n215:         self._context_reset_attempted = False\n216: \n217:     def feature_complete(self, feature):\n218:         if feature is not self._active_feature:\n219:             return\n220:         if self.busy:\n221:             raise RuntimeError(\"Feature completed while commands are still pending\")\n222:         feature.mark_completed()\n223:         if feature.completion_message:\n224:             self._completed_messages.append(feature.completion_message)\n225:         self._finish_standard_output_context(feature)\n226:         self._schedule_feature_cleanup(feature, \"completion\")\n227:         self._active_feature = None\n228:         self._active_commands = ()\n229:         if not self._cleanup:\n230:             self._activate_next_feature()\n231: \n232:     def register_cleanup(self, feature, action):\n233:         if not isinstance(action, CleanupAction):\n234:             raise TypeError(\"cleanup must be a CleanupAction\")\n235:         self._cleanup_actions.setdefault(feature, []).append(action)\n236: \n237:     def with_standard_output(self, feature, callback):\n238:         \"\"\"Run a feature callback after standard console output is available.\"\"\"\n239:         if feature is not self._active_feature:\n240:             raise RuntimeError(\"Inactive feature requested standard console output\")\n241:         if self.busy or self._standard_output_context:\n242:             raise RuntimeError(\"Cannot start a standard console output context while busy\")\n243:         self._standard_output_context = _StandardOutputContext(feature, callback)\n244:         self.submit_block(feature, CommandSequence(\"console-output-inspect\", [\n245:             CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),\n246:         ]))\n247: \n248:     def _schedule_feature_cleanup(self, feature, trigger):\n249:         actions = self._cleanup_actions.pop(feature, [])\n250:         for action in actions:\n251:             if (trigger == \"completion\" and action.on_completion) or (\n252:                 trigger == \"interruption\" and action.on_interruption\n253:             ):\n254:                 self.logger.debug(f\"Scheduling cleanup {action.name} after {trigger}\")\n255:                 self._cleanup.extend(action.block.flatten())\n256: \n257:     def on_output(self, output):\n258:         if not isinstance(output, Data):\n259:             raise TypeError(\"commander output must be terminal.Data\")\n260:         if not output:\n261:             return output\n262:         if self._inflight:\n263:             if self._call_feature(self._inflight.on_output, output):\n264:                 return output\n265:             if self._active_feature and self._call_feature(self._active_feature.on_output, output):\n266:                 return output\n267:         self._inspect_output(output)\n268:         return output\n269: \n270:     def on_state(self, state, output):\n271:         \"\"\"Called by the driver for every recognized serial state.\"\"\"\n272:         self._current_state = state\n273:         self._callback_failed = False\n274:         if state == FOSCliState.CMD_PROMPT:\n275:             context = self._extract_prompt_context(output)\n276:             if context is not None:\n277:                 self._prompt_context = context\n278:             # Some releases return directly to a usable prompt after login,\n279:             # without a Welcome banner. The prompt also ends session recovery.\n280:             self._authenticated_once = True\n281:             self._recovering = False\n282:         if self._pending_feature_error is not None:\n283:             if state == FOSCliState.CMD_PROMPT:\n284:                 self._recover_feature_error()\n285:             elif state == FOSCliState.SESSION_LOST:\n286:                 self._session_epoch += 1\n287:                 self._recovering = True\n288:             elif state == FOSCliState.CREDENTIAL_ACCEPTED:\n289:                 self._authenticated_once = True\n290:                 self._recovering = False\n291:             return\n292:         self.on_output(output)\n293:         if self._callback_failed:\n294:             if state == FOSCliState.CMD_PROMPT:\n295:                 self._recover_feature_error()\n296:             return\n297:         if self._pending_feature_error is not None:\n298:             if state == FOSCliState.CMD_PROMPT:\n299:                 self._recover_feature_error()\n300:             return\n301: \n302:         if state == FOSCliState.SESSION_LOST:\n303:             self._handle_session_loss()\n304:             return\n305:         if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:\n306:             # Password updates can return to login without the explicit\n307:             # SESSION_LOST banner. Requeue the active command block so it is\n308:             # applied after the driver restores an accepted login.\n309:             self._handle_session_loss()\n310:             return\n311:         if state == FOSCliState.CREDENTIAL_ACCEPTED:\n312:             self._authenticated_once = True\n313:             self._recovering = False\n314:             return\n315:         if self._inflight and state in (\n316:             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n317:         ):\n318:             self._complete_inflight(state)\n319:             return\n320: \n321:         if state == FOSCliState.CMD_PROMPT and not self._recovering:\n322:             self._dispatch_next()\n323:         if self._callback_failed and state == FOSCliState.CMD_PROMPT:\n324:             self._recover_feature_error()\n325: \n326:     def on_prompt_echo(self, output):\n327:         \"\"\"Handle a prompt line that had trailing text after the prompt token.\"\"\"\n328:         if self.on_output(output).discarded:\n329:             return\n330:         self.logger.debug(\"Prompt had unexpected trailing output; requesting a clean prompt\")\n331:         self.terminal.write(b\"\\r\")\n332: \n333:     def _inspect_output(self, output):\n334:         if self._recovering:\n335:             output.discard()\n336: \n337:     def on_idle_prompt(self):\n338:         \"\"\"Recover errors or dispatch work while idle at a known prompt.\"\"\"\n339:         if self._inflight or self._recovering:\n340:             return\n341:         if self._pending_feature_error is not None:\n342:             # The driver calls this after a read timeout at a known CLI prompt.\n343:             # on_state has since recorded TN_TIMEOUT, so recover explicitly.\n344:             self._recover_feature_error(at_idle_prompt=True)\n345:             return\n346:         if self._pending or self._cleanup or self._active_feature is None:\n347:             self._dispatch_next()\n348: \n349:     def _activate_next_feature(self):\n350:         if self._ready or self._active_feature or self._recovering:\n351:             return\n352:         if not self._features:\n353:             if self._cleanup:\n354:                 return\n355:             self._ready = True\n356:             self.terminal.close()\n357:             if not self._startup_complete:\n358:                 self._startup_complete = True\n359:                 elapsed = datetime.datetime.now() - self._start_time\n360:                 if self._feature_errors:\n361:                     failed = \", \".join(name for name, _error in self._feature_errors)\n362:                     self.logger.error(\n363:                         \"Bootstrap reached the end with %d feature error(s) in %s; \"\n364:                         \"failed work: %s\",\n365:                         len(self._feature_errors),\n366:                         elapsed,\n367:                         failed,\n368:                     )\n369:                 else:\n370:                     self.logger.info(f\"Startup complete in {elapsed}\")\n371:             else:\n372:                 while self._completed_messages:\n373:                     self.logger.info(self._completed_messages.popleft())\n374:             return\n375:         self._active_feature = self._features.popleft()\n376:         self.logger.info(f\"Activating feature {self._active_feature.name}\")\n377:         self._call_feature(self._active_feature.begin_activation)\n378:         if self._pending_feature_error is None:\n379:             self._call_feature(self._active_feature.activate)\n380: \n381:     def _dispatch_next(self):\n382:         if self._inflight or self._recovering or self._pending_feature_error is not None:\n383:             return\n384:         if not self._restore_replay_context():\n385:             return\n386:         if not self._cleanup and self._active_feature is None:\n387:             self._activate_next_feature()\n388:             if self._active_feature is None:\n389:                 return\n390:         if self._cleanup:\n391:             spec = self._cleanup.popleft()\n392:             self._in_cleanup = True\n393:             block_index = None\n394:         elif not self._pending:\n395:             self._call_feature(self._active_feature.on_block_complete)\n396:             return\n397:         else:\n398:             spec = self._pending.popleft()\n399:             self._in_cleanup = False\n400:             block_index = len(self._active_commands) - len(self._pending) - 1\n401:         self._dispatch_command(spec, block_index)\n402: \n403:     def _dispatch_command(self, spec, block_index=None):\n404:         self._attempt_number += 1\n405:         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n406:         self._inflight.prompt_context_before = self._prompt_context\n407:         self._inflight.block_index = block_index\n408:         self._inflight.retry_count = (\n409:             self._cleanup_retries.get(id(spec), 0)\n410:             if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n411:         )\n412:         if self._active_feature and not self._in_context_reset:\n413:             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n414:             if self._pending_feature_error is not None:\n415:                 return\n416:         if spec.suppress_output:\n417:             self._suppression.enter_context(self.terminal.suppress_output())\n418:         self.logger.log(\n419:             TRACE_LEVEL,\n420:             f\"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/\"\n421:             f\"{spec.line!r}\"\n422:         )\n423:         self.terminal.write(f\"{spec.line}\\r\")\n424: \n425:     def _complete_inflight(self, state):\n426:         attempt = self._inflight\n427:         self._inflight = None\n428:         self._suppression.close()\n429:         self._suppression = ExitStack()\n430:         attempt.prompt_context_after = self._prompt_context\n431:         if self._in_context_reset:\n432:             self._in_context_reset = False\n433:             self._dispatch_next()\n434:             return\n435:         if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n436:             self._handle_context_loss(attempt)\n437:             if self._pending_feature_error is not None:\n438:                 self._recover_feature_error()\n439:             else:\n440:                 self._dispatch_next()\n441:             return\n442:         try:\n443:             self._validate_completion(attempt, state)\n444:         except RuntimeError as error:\n445:             if state != FOSCliState.CMD_PROMPT:\n446:                 # An interactive prompt cannot safely advance to another feature.\n447:                 raise\n448:             self._handle_work_error(error)\n449:             if self._pending_feature_error is not None:\n450:                 self._recover_feature_error()\n451:             return\n452:         if self._in_cleanup:\n453:             self._cleanup_retries.pop(id(attempt.spec), None)\n454:             self._in_cleanup = False\n455:             self._dispatch_next()\n456:             return\n457:         if self._is_standard_output_command(attempt.spec):\n458:             self._complete_standard_output_command(attempt)\n459:             if self._pending_feature_error is not None:\n460:                 return\n461:             if not self._recovering:\n462:                 self._dispatch_next()\n463:             return\n464:         completed_feature = self._active_feature\n465:         self._call_feature(completed_feature.on_command_executed, attempt, state)\n466:         if self._pending_feature_error is not None:\n467:             return\n468:         # The callback may have installed another block (confirmation/query path).\n469:         if not self.busy and self._active_feature is completed_feature:\n470:             self._call_feature(completed_feature.on_block_complete)\n471:         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n472:             self._dispatch_next()\n473: \n474:     @staticmethod\n475:     def _validate_completion(attempt, state):\n476:         if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n477:             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n478:         ):\n479:             raise RuntimeError(\n480:                 f\"FortiOS command {attempt.spec.line!r} failed \"\n481:                 f\"(return code {failure.group(1).decode()})\"\n482:             )\n483:         expected = attempt.spec.expected_completion_state\n484:         if expected is not None and state != expected:\n485:             raise RuntimeError(\n486:                 \"CLI command completed at unexpected prompt: \"\n487:                 f\"expected {expected.name}, received {state.name}\"\n488:             )\n489: \n490:     def _prompt_context_changed(self, attempt):\n491:         before = attempt.prompt_context_before\n492:         after = attempt.prompt_context_after\n493:         return (\n494:             before is not None\n495:             and after is not None\n496:             and before != after\n497:             and not self._command_may_change_context(attempt.spec)\n498:         )\n499: \n500:     def _handle_context_loss(self, attempt):\n501:         reason = (\n502:             \"CLI context changed from \"\n503:             f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n504:             f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n505:         )\n506:         if self._in_cleanup:\n507:             self._handle_work_error(RuntimeError(\n508:                 f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n509:             ))\n510:             return\n511:         action = self._call_feature(self._active_feature.on_context_loss, attempt)\n512:         if self._pending_feature_error is not None:\n513:             return\n514:         if action == ContextLossAction.RESTART_BLOCK:\n515:             self._restart_active_block(attempt, reason)\n516:         elif action == ContextLossAction.FAIL:\n517:             self._handle_work_error(RuntimeError(\n518:                 f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n519:             ))\n520:         else:\n521:             self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n522: \n523:     def _restore_replay_context(self):\n524:         \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n525:         target = self._replay_context_target\n526:         if target is None:\n527:             return True\n528:         if self._prompt_context == target:\n529:             self._replay_context_target = None\n530:             return True\n531:         if self._context_reset_attempted:\n532:             self._handle_work_error(RuntimeError(\n533:                 \"Unable to restore CLI context before replay: expected \"\n534:                 f\"{self._format_prompt_context(target)}, received \"\n535:                 f\"{self._format_prompt_context(self._prompt_context or ())}\"\n536:             ))\n537:             if self._pending_feature_error is not None:\n538:                 self._recover_feature_error()\n539:             return False\n540:         self._context_reset_attempted = True\n541:         self._in_context_reset = True\n542:         self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n543:         return False\n544: \n545:     @staticmethod\n546:     def _command_may_change_context(spec):\n547:         if spec.continuation:\n548:             return False\n549:         command = spec.line.strip().lower()\n550:         return (\n551:             command.startswith((\"config \", \"edit \"))\n552:             or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n553:             or command == \"set vdom-mode multi-vdom\"\n554:         )\n555: \n556:     @staticmethod\n557:     def _extract_prompt_context(output):\n558:         data = bytes(output)\n559:         matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n560:         if not matches:\n561:             return None\n562:         return tuple(\n563:             item.decode(errors=\"replace\")\n564:             for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n565:         )\n566: \n567:     @staticmethod\n568:     def _format_prompt_context(context):\n569:         return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n570: \n571:     def _is_standard_output_command(self, spec):\n572:         context = self._standard_output_context\n573:         return context is not None and (\n574:             spec.line == self._CONSOLE_INSPECT_LINE\n575:             or (context.phase == \"set-standard\" and not self._pending)\n576:         )\n577: \n578:     def _complete_standard_output_command(self, attempt):\n579:         context = self._standard_output_context\n580:         if attempt.spec.line == self._CONSOLE_INSPECT_LINE:\n581:             match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))\n582:             if not match or match.group(1) == b\"standard\":\n583:                 if not match:\n584:                     self.logger.warning(\"Could not determine console output mode; assuming standard output\")\n585:                 self._start_standard_output_callback(context)\n586:                 return\n587:             context.phase = \"set-standard\"\n588:             self.submit_block(context.feature, ConfigBlock(\"system console\", [\n589:                 self._CONSOLE_STANDARD_LINE,\n590:             ]))\n591:             return\n592:         if context.phase == \"set-standard\":\n593:             context.restore = True\n594:             self._start_standard_output_callback(context)\n595: \n596:     def _start_standard_output_callback(self, context):\n597:         context.phase = \"active\"\n598:         self._call_feature(context.callback)\n599: \n600:     def _finish_standard_output_context(self, feature):\n601:         context = self._standard_output_context\n602:         if context is None or context.feature is not feature:\n603:             return\n604:         self._standard_output_context = None\n605:         if context.restore:\n606:             self._cleanup.extend(ConfigBlock(\"system console\", [\n607:                 \"set output more\",\n608:             ]).flatten())\n609: \n610:     def _handle_session_loss(self):\n611:         self._session_epoch += 1\n612:         self._recovering = True\n613:         if not self._inflight:\n614:             return\n615:         attempt = self._inflight\n616:         self._inflight = None\n617:         self._suppression.close()\n618:         self._suppression = ExitStack()\n619:         if self._in_context_reset:\n620:             # Login may itself restore the target scope. The pending replay\n621:             # stays bounded by the original command's recovery allowance.\n622:             self._in_context_reset = False\n623:             return\n624:         if self._in_cleanup:\n625:             retries = self._cleanup_retries.get(id(attempt.spec), 0)\n626:             if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n627:                 self._handle_work_error(RuntimeError(\n628:                     f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n629:                     \"retry limit reached\"\n630:                 ))\n631:                 return\n632:             self._cleanup_retries[id(attempt.spec)] = retries + 1\n633:             self._cleanup.appendleft(attempt.spec)\n634:             self._in_cleanup = False\n635:             return\n636:         self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n637:         action = self._call_feature(\n638:             self._active_feature.on_session_loss,\n639:             attempt,\n640:         )\n641:         if self._pending_feature_error is not None:\n642:             return\n643:         self.logger.info(\n644:             f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n645:         )\n646:         action_handlers = {\n647:             SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n648:                 attempt, \"session lost\"\n649:             ),\n650:             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n651:             SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n652:             SessionLossAction.FAIL: lambda: self._handle_work_error(\n653:                 RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n654:             ),\n655:             SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n656:         }\n657:         action_handlers[action]()\n658: \n659:     def _restart_active_block(self, attempt, reason):\n660:         retries = self._recovery_retries.get(attempt.block_index, 0)\n661:         if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n662:             self._handle_work_error(RuntimeError(\n663:                 f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n664:                 f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n665:             ))\n666:             return\n667:         self._recovery_retries[attempt.block_index] = retries + 1\n668:         self._pending = deque(self._active_commands)\n669:         self._replay_context_target = self._block_prompt_context\n670:         self._context_reset_attempted = False\n671:         self.logger.warning(\n672:             \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n673:             reason, self._active_feature.name, attempt.spec.line,\n674:             retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n675:         )\n676: \n677:     def enqueue_runtime_feature(self, feature):\n678:         return self.enqueue_runtime_features([feature])\n679: \n680:     def enqueue_runtime_features(self, features):\n681:         if not self._ready or self.busy:\n682:             return False\n683:         self._ready = False\n684:         self._completed_messages.clear()\n685:         for feature in reversed(features):\n686:             self._features.appendleft(feature)\n687:         return True\n\n(End of file - total 687 lines)\n</content>",
    "title": "source/head/fortinet/common/fos_commander.py",
    "metadata": {
      "preview": "\"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n\nimport datetime\nimport re\nfrom collections import deque\nfrom contextlib import ExitStack\nfrom dataclasses import dataclass\n\nfrom .cli_commands import (\n    CleanupAction,\n    CommandAttempt,\n    CommandSequence,\n    CommandSpec,\n    ConfigBlock,\n    ContextLossAction,\n    SessionLossAction,\n    flatten_commands,\n)\nfrom .terminal import Data\nfrom .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_commander.py",
        "text": "\"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n\nimport datetime\nimport re\nfrom collections import deque\nfrom contextlib import ExitStack\nfrom dataclasses import dataclass\n\nfrom .cli_commands import (\n    CleanupAction,\n    CommandAttempt,\n    CommandSequence,\n    CommandSpec,\n    ConfigBlock,\n    ContextLossAction,\n    SessionLossAction,\n    flatten_commands,\n)\nfrom .terminal import Data\nfrom .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n\nDISPATCHABLE_COMPLETION_STATES = {\n    FOSCliState.CMD_PROMPT,\n    FOSCliState.CONFIRMATION,\n    FOSCliState.MULTILINE_PROMPT,\n}\nCOMMAND_FAILURE_PATTERN = re.compile(\n    rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n)\nCLI_PROMPT_CONTEXT_PATTERN = re.compile(\n    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n)\n\n\n@dataclass\nclass _StandardOutputContext:\n    feature: object\n    callback: object\n    phase: str = \"inspect\"\n    restore: bool = False\n\n\nclass FOSCommander:\n    MAX_COMMAND_RECOVERY_RETRIES = 1\n    _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n    _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n    _CONSOLE_STANDARD_LINE = \"set output standard\"\n\n    def __init__(self, terminal, logger, continue_on_error=False):\n        self.terminal = terminal\n        self.logger = logger\n        self._features = deque()\n        self._active_feature = None\n        self._active_commands = ()\n        self._pending = deque()\n        self._inflight = None\n        self._attempt_number = 0\n        self._session_epoch = 0\n        self._recovering = False\n        self._cleanup = deque()\n        self._cleanup_actions = {}\n        self._in_cleanup = False\n        self._standard_output_context = None\n        self._suppression = ExitStack()\n        self._ready = False\n        self._startup_complete = False\n        self._feature_errors = []\n        self._authenticated_once = False\n        self._completed_messages = deque()\n        self._start_time = datetime.datetime.now()\n        self._continue_on_error = continue_on_error\n        self._pending_feature_error = None\n        self._current_state = None\n        self._callback_failed = False\n        self._prompt_context = None\n        self._block_prompt_context = None\n        self._recovery_retries = {}\n        self._cleanup_retries = {}\n        self._replay_context_target = None\n        self._context_reset_attempted = False\n        self._in_context_reset = False\n\n    def _call_feature(self, callback, *args):\n        \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n        try:\n            return callback(*args)\n        except Exception as error:\n            self._handle_work_error(error, from_callback=True)\n            return None\n\n    def _handle_work_error(self, error, *, from_callback=False):\n        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n        if not self._continue_on_error:\n            raise error\n        if from_callback:\n            self.logger.exception(\"Bootstrap feature callback failed\")\n        else:\n            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n        self._pending_feature_error = error\n        self._callback_failed = True\n\n    def _recover_feature_error(self, *, at_idle_prompt=False):\n        error = self._pending_feature_error\n        if error is None or (\n            self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n        ):\n            return False\n        failed_work = self.continue_after_error(error, at_command_prompt=True)\n        if failed_work is None:\n            return False\n        self._pending_feature_error = None\n        self.logger.error(\n            \"Bootstrap work %s failed; continuing with remaining features \"\n            \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n            failed_work,\n        )\n        self._dispatch_next()\n        return True\n\n    @property\n    def ready(self):\n        return self._ready\n\n    @property\n    def busy(self):\n        return self._inflight is not None or bool(self._pending) or bool(self._cleanup)\n\n    @property\n    def startup_complete(self):\n        \"\"\"Whether the initial feature queue has drained, with or without errors.\"\"\"\n        return self._startup_complete\n\n    @property\n    def feature_errors(self):\n        \"\"\"Bootstrap feature errors recorded while best-effort mode is active.\"\"\"\n        return tuple(self._feature_errors)\n\n    def continue_after_error(self, error, at_command_prompt):\n        \"\"\"Skip failed work only when the CLI is back at a usable prompt.\n\n        A login rejection after the driver's credential recovery attempts, or\n        an error during an interactive prompt, cannot be recovered by sending\n        the next feature's commands, so automatic bootstrap must stop.\n        \"\"\"\n        if not at_command_prompt or self._ready:\n            return None\n        if self._active_feature is None and not self._in_cleanup:\n            return None\n\n        if self._active_feature is not None:\n            failed_name = self._active_feature.name\n            self._pending.clear()\n            self._active_commands = ()\n            self._inflight = None\n            self._suppression.close()\n            self._suppression = ExitStack()\n            self._finish_standard_output_context(self._active_feature)\n            self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n            self._active_feature = None\n        else:\n            failed_name = \"cleanup\"\n            self._inflight = None\n            self._suppression.close()\n            self._suppression = ExitStack()\n\n        self._in_cleanup = False\n        self._replay_context_target = None\n        self._in_context_reset = False\n        self._cleanup_retries.clear()\n        self._feature_errors.append((failed_name, str(error)))\n        return failed_name\n\n    def record_feature_error(self, name, error):\n        \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n        self._feature_errors.append((name, str(error)))\n        self.logger.info(\"Using recovery for %s: %s\", name, error)\n\n    def resolve_feature_error(self, name, resolution):\n        \"\"\"Clear a recoverable feature error after its condition is resolved.\"\"\"\n        remaining = [\n            (feature_name, error)\n            for feature_name, error in self._feature_errors\n            if feature_name != name\n        ]\n        resolved_count = len(self._feature_errors) - len(remaining)\n        if resolved_count:\n            self._feature_errors = remaining\n            self.logger.info(\n                \"Resolved %s bootstrap recovery after %s\",\n                name,\n                resolution,\n            )\n\n    def start(self, features):\n        self._features.extend(features)\n\n    def tick(self):\n        if self._pending_feature_error is not None:\n            return\n        if self._active_feature and hasattr(self._active_feature, \"tick\"):\n            self._call_feature(self._active_feature.tick)\n\n    def submit_block(self, feature, block):\n        if feature is not self._active_feature:\n            raise RuntimeError(\"Inactive feature attempted to submit commands\")\n        if self.busy:\n            raise RuntimeError(\"Cannot replace an active command block\")\n        commands = tuple(flatten_commands(block))\n        self._active_commands = commands\n        self._pending = deque(commands)\n        self._block_prompt_context = self._prompt_context\n        self._recovery_retries = {}\n        self._replay_context_target = None\n        self._context_reset_attempted = False\n\n    def feature_complete(self, feature):\n        if feature is not self._active_feature:\n            return\n        if self.busy:\n            raise RuntimeError(\"Feature completed while commands are still pending\")\n        feature.mark_completed()\n        if feature.completion_message:\n            self._completed_messages.append(feature.completion_message)\n        self._finish_standard_output_context(feature)\n        self._schedule_feature_cleanup(feature, \"completion\")\n        self._active_feature = None\n        self._active_commands = ()\n        if not self._cleanup:\n            self._activate_next_feature()\n\n    def register_cleanup(self, feature, action):\n        if not isinstance(action, CleanupAction):\n            raise TypeError(\"cleanup must be a CleanupAction\")\n        self._cleanup_actions.setdefault(feature, []).append(action)\n\n    def with_standard_output(self, feature, callback):\n        \"\"\"Run a feature callback after standard console output is available.\"\"\"\n        if feature is not self._active_feature:\n            raise RuntimeError(\"Inactive feature requested standard console output\")\n        if self.busy or self._standard_output_context:\n            raise RuntimeError(\"Cannot start a standard console output context while busy\")\n        self._standard_output_context = _StandardOutputContext(feature, callback)\n        self.submit_block(feature, CommandSequence(\"console-output-inspect\", [\n            CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),\n        ]))\n\n    def _schedule_feature_cleanup(self, feature, trigger):\n        actions = self._cleanup_actions.pop(feature, [])\n        for action in actions:\n            if (trigger == \"completion\" and action.on_completion) or (\n                trigger == \"interruption\" and action.on_interruption\n            ):\n                self.logger.debug(f\"Scheduling cleanup {action.name} after {trigger}\")\n                self._cleanup.extend(action.block.flatten())\n\n    def on_output(self, output):\n        if not isinstance(output, Data):\n            raise TypeError(\"commander output must be terminal.Data\")\n        if not output:\n            return output\n        if self._inflight:\n            if self._call_feature(self._inflight.on_output, output):\n                return output\n            if self._active_feature and self._call_feature(self._active_feature.on_output, output):\n                return output\n        self._inspect_output(output)\n        return output\n\n    def on_state(self, state, output):\n        \"\"\"Called by the driver for every recognized serial state.\"\"\"\n        self._current_state = state\n        self._callback_failed = False\n        if state == FOSCliState.CMD_PROMPT:\n            context = self._extract_prompt_context(output)\n            if context is not None:\n                self._prompt_context = context\n            # Some releases return directly to a usable prompt after login,\n            # without a Welcome banner. The prompt also ends session recovery.\n            self._authenticated_once = True\n            self._recovering = False\n        if self._pending_feature_error is not None:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            elif state == FOSCliState.SESSION_LOST:\n                self._session_epoch += 1\n                self._recovering = True\n            elif state == FOSCliState.CREDENTIAL_ACCEPTED:\n                self._authenticated_once = True\n                self._recovering = False\n            return\n        self.on_output(output)\n        if self._callback_failed:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            return\n        if self._pending_feature_error is not None:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            return\n\n        if state == FOSCliState.SESSION_LOST:\n            self._handle_session_loss()\n            return\n        if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:\n            # Password updates can return to login without the explicit\n            # SESSION_LOST banner. Requeue the active command block so it is\n            # applied after the driver restores an accepted login.\n            self._handle_session_loss()\n            return\n        if state == FOSCliState.CREDENTIAL_ACCEPTED:\n            self._authenticated_once = True\n            self._recovering = False\n            return\n        if self._inflight and state in (\n            self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n        ):\n            self._complete_inflight(state)\n            return\n\n        if state == FOSCliState.CMD_PROMPT and not self._recovering:\n            self._dispatch_next()\n        if self._callback_failed and state == FOSCliState.CMD_PROMPT:\n            self._recover_feature_error()\n\n    def on_prompt_echo(self, output):\n        \"\"\"Handle a prompt line that had trailing text after the prompt token.\"\"\"\n        if self.on_output(output).discarded:\n            return\n        self.logger.debug(\"Prompt had unexpected trailing output; requesting a clean prompt\")\n        self.terminal.write(b\"\\r\")\n\n    def _inspect_output(self, output):\n        if self._recovering:\n            output.discard()\n\n    def on_idle_prompt(self):\n        \"\"\"Recover errors or dispatch work while idle at a known prompt.\"\"\"\n        if self._inflight or self._recovering:\n            return\n        if self._pending_feature_error is not None:\n            # The driver calls this after a read timeout at a known CLI prompt.\n            # on_state has since recorded TN_TIMEOUT, so recover explicitly.\n            self._recover_feature_error(at_idle_prompt=True)\n            return\n        if self._pending or self._cleanup or self._active_feature is None:\n            self._dispatch_next()\n\n    def _activate_next_feature(self):\n        if self._ready or self._active_feature or self._recovering:\n            return\n        if not self._features:\n            if self._cleanup:\n                return\n            self._ready = True\n            self.terminal.close()\n            if not self._startup_complete:\n                self._startup_complete = True\n                elapsed = datetime.datetime.now() - self._start_time\n                if self._feature_errors:\n                    failed = \", \".join(name for name, _error in self._feature_errors)\n                    self.logger.error(\n                        \"Bootstrap reached the end with %d feature error(s) in %s; \"\n                        \"failed work: %s\",\n                        len(self._feature_errors),\n                        elapsed,\n                        failed,\n                    )\n                else:\n                    self.logger.info(f\"Startup complete in {elapsed}\")\n            else:\n                while self._completed_messages:\n                    self.logger.info(self._completed_messages.popleft())\n            return\n        self._active_feature = self._features.popleft()\n        self.logger.info(f\"Activating feature {self._active_feature.name}\")\n        self._call_feature(self._active_feature.begin_activation)\n        if self._pending_feature_error is None:\n            self._call_feature(self._active_feature.activate)\n\n    def _dispatch_next(self):\n        if self._inflight or self._recovering or self._pending_feature_error is not None:\n            return\n        if not self._restore_replay_context():\n            return\n        if not self._cleanup and self._active_feature is None:\n            self._activate_next_feature()\n            if self._active_feature is None:\n                return\n        if self._cleanup:\n            spec = self._cleanup.popleft()\n            self._in_cleanup = True\n            block_index = None\n        elif not self._pending:\n            self._call_feature(self._active_feature.on_block_complete)\n            return\n        else:\n            spec = self._pending.popleft()\n            self._in_cleanup = False\n            block_index = len(self._active_commands) - len(self._pending) - 1\n        self._dispatch_command(spec, block_index)\n\n    def _dispatch_command(self, spec, block_index=None):\n        self._attempt_number += 1\n        self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n        self._inflight.prompt_context_before = self._prompt_context\n        self._inflight.block_index = block_index\n        self._inflight.retry_count = (\n            self._cleanup_retries.get(id(spec), 0)\n            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n        )\n        if self._active_feature and not self._in_context_reset:\n            self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n            if self._pending_feature_error is not None:\n                return\n        if spec.suppress_output:\n            self._suppression.enter_context(self.terminal.suppress_output())\n        self.logger.log(\n            TRACE_LEVEL,\n            f\"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/\"\n            f\"{spec.line!r}\"\n        )\n        self.terminal.write(f\"{spec.line}\\r\")\n\n    def _complete_inflight(self, state):\n        attempt = self._inflight\n        self._inflight = None\n        self._suppression.close()\n        self._suppression = ExitStack()\n        attempt.prompt_context_after = self._prompt_context\n        if self._in_context_reset:\n            self._in_context_reset = False\n            self._dispatch_next()\n            return\n        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n            self._handle_context_loss(attempt)\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            else:\n                self._dispatch_next()\n            return\n        try:\n            self._validate_completion(attempt, state)\n        except RuntimeError as error:\n            if state != FOSCliState.CMD_PROMPT:\n                # An interactive prompt cannot safely advance to another feature.\n                raise\n            self._handle_work_error(error)\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            return\n        if self._in_cleanup:\n            self._cleanup_retries.pop(id(attempt.spec), None)\n            self._in_cleanup = False\n            self._dispatch_next()\n            return\n        if self._is_standard_output_command(attempt.spec):\n            self._complete_standard_output_command(attempt)\n            if self._pending_feature_error is not None:\n                return\n            if not self._recovering:\n                self._dispatch_next()\n            return\n        completed_feature = self._active_feature\n        self._call_feature(completed_feature.on_command_executed, attempt, state)\n        if self._pending_feature_error is not None:\n            return\n        # The callback may have installed another block (confirmation/query path).\n        if not self.busy and self._active_feature is completed_feature:\n            self._call_feature(completed_feature.on_block_complete)\n        if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n            self._dispatch_next()\n\n    @staticmethod\n    def _validate_completion(attempt, state):\n        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n            failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n        ):\n            raise RuntimeError(\n                f\"FortiOS command {attempt.spec.line!r} failed \"\n                f\"(return code {failure.group(1).decode()})\"\n            )\n        expected = attempt.spec.expected_completion_state\n        if expected is not None and state != expected:\n            raise RuntimeError(\n                \"CLI command completed at unexpected prompt: \"\n                f\"expected {expected.name}, received {state.name}\"\n            )\n\n    def _prompt_context_changed(self, attempt):\n        before = attempt.prompt_context_before\n        after = attempt.prompt_context_after\n        return (\n            before is not None\n            and after is not None\n            and before != after\n            and not self._command_may_change_context(attempt.spec)\n        )\n\n    def _handle_context_loss(self, attempt):\n        reason = (\n            \"CLI context changed from \"\n            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n        )\n        if self._in_cleanup:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n            ))\n            return\n        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n        if self._pending_feature_error is not None:\n            return\n        if action == ContextLossAction.RESTART_BLOCK:\n            self._restart_active_block(attempt, reason)\n        elif action == ContextLossAction.FAIL:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n            ))\n        else:\n            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n\n    def _restore_replay_context(self):\n        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n        target = self._replay_context_target\n        if target is None:\n            return True\n        if self._prompt_context == target:\n            self._replay_context_target = None\n            return True\n        if self._context_reset_attempted:\n            self._handle_work_error(RuntimeError(\n                \"Unable to restore CLI context before replay: expected \"\n                f\"{self._format_prompt_context(target)}, received \"\n                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n            ))\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            return False\n        self._context_reset_attempted = True\n        self._in_context_reset = True\n        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n        return False\n\n    @staticmethod\n    def _command_may_change_context(spec):\n        if spec.continuation:\n            return False\n        command = spec.line.strip().lower()\n        return (\n            command.startswith((\"config \", \"edit \"))\n            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n            or command == \"set vdom-mode multi-vdom\"\n        )\n\n    @staticmethod\n    def _extract_prompt_context(output):\n        data = bytes(output)\n        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n        if not matches:\n            return None\n        return tuple(\n            item.decode(errors=\"replace\")\n            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n        )\n\n    @staticmethod\n    def _format_prompt_context(context):\n        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n\n    def _is_standard_output_command(self, spec):\n        context = self._standard_output_context\n        return context is not None and (\n            spec.line == self._CONSOLE_INSPECT_LINE\n            or (context.phase == \"set-standard\" and not self._pending)\n        )\n\n    def _complete_standard_output_command(self, attempt):\n        context = self._standard_output_context\n        if attempt.spec.line == self._CONSOLE_INSPECT_LINE:\n            match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))\n            if not match or match.group(1) == b\"standard\":\n                if not match:\n                    self.logger.warning(\"Could not determine console output mode; assuming standard output\")\n                self._start_standard_output_callback(context)\n                return\n            context.phase = \"set-standard\"\n            self.submit_block(context.feature, ConfigBlock(\"system console\", [\n                self._CONSOLE_STANDARD_LINE,\n            ]))\n            return\n        if context.phase == \"set-standard\":\n            context.restore = True\n            self._start_standard_output_callback(context)\n\n    def _start_standard_output_callback(self, context):\n        context.phase = \"active\"\n        self._call_feature(context.callback)\n\n    def _finish_standard_output_context(self, feature):\n        context = self._standard_output_context\n        if context is None or context.feature is not feature:\n            return\n        self._standard_output_context = None\n        if context.restore:\n            self._cleanup.extend(ConfigBlock(\"system console\", [\n                \"set output more\",\n            ]).flatten())\n\n    def _handle_session_loss(self):\n        self._session_epoch += 1\n        self._recovering = True\n        if not self._inflight:\n            return\n        attempt = self._inflight\n        self._inflight = None\n        self._suppression.close()\n        self._suppression = ExitStack()\n        if self._in_context_reset:\n            # Login may itself restore the target scope. The pending replay\n            # stays bounded by the original command's recovery allowance.\n            self._in_context_reset = False\n            return\n        if self._in_cleanup:\n            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n                self._handle_work_error(RuntimeError(\n                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n                    \"retry limit reached\"\n                ))\n                return\n            self._cleanup_retries[id(attempt.spec)] = retries + 1\n            self._cleanup.appendleft(attempt.spec)\n            self._in_cleanup = False\n            return\n        self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n        action = self._call_feature(\n            self._active_feature.on_session_loss,\n            attempt,\n        )\n        if self._pending_feature_error is not None:\n            return\n        self.logger.info(\n            f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n        )\n        action_handlers = {\n            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n                attempt, \"session lost\"\n            ),\n            SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n            SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n            SessionLossAction.FAIL: lambda: self._handle_work_error(\n                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n            ),\n            SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n        }\n        action_handlers[action]()\n\n    def _restart_active_block(self, attempt, reason):\n        retries = self._recovery_retries.get(attempt.block_index, 0)\n        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n            ))\n            return\n        self._recovery_retries[attempt.block_index] = retries + 1\n        self._pending = deque(self._active_commands)\n        self._replay_context_target = self._block_prompt_context\n        self._context_reset_attempted = False\n        self.logger.warning(\n            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n            reason, self._active_feature.name, attempt.spec.line,\n            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n        )\n\n    def enqueue_runtime_feature(self, feature):\n        return self.enqueue_runtime_features([feature])\n\n    def enqueue_runtime_features(self, features):\n        if not self._ready or self.busy:\n            return False\n        self._ready = False\n        self._completed_messages.clear()\n        for feature in reversed(features):\n            self._features.appendleft(feature)\n        return True",
        "lineStart": 1,
        "lineEnd": 687,
        "totalLines": 687,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716210904,
      "end": 1793716210909
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d14cdf001Q8ADQpU9VTE0UL",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d1375c001FIizK8w9R74JaS",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 56517,
    "input": 5265,
    "output": 20,
    "reasoning": 32,
    "cache": {
      "read": 51200,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d1375c001FIizK8w9R74JaS",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716205405,
    "completed": 1793716210913
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 56517,
    "input": 5265,
    "output": 20,
    "reasoning": 32,
    "cache": {
      "read": 51200,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 7
step-start
{
  "type": "step-start",
  "id": "prt_1a1d15e29001PcM5wn7PeiFTor",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d14ce4001k1NWsz8TzXeS62"
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/terminal.py"
}

Output

<path>/source/head/fortinet/common/terminal.py</path>
<type>file</type>
<content>
1: import cmd
2: import logging
3: import re
4: import threading
5: import time
6: from collections import deque
7: from contextlib import contextmanager
8: 
9: from .common import TRACE_LEVEL
10: from .env import get_env
11: 
12: 
13: DEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024
14: BUFFER_LIMIT_ENV = "FOS_TERMINAL_BUFFER_LIMIT_BYTES"
15: READ_POLL_SECONDS = 0.001
16: RAW_SERIAL_LOG_ENV = "FOS_LOG_RAW_SERIAL"
17: 
18: 
19: def terminal_buffer_limit_bytes():
20:     configured = get_env(BUFFER_LIMIT_ENV)
21:     if not configured:
22:         return DEFAULT_BUFFER_LIMIT_BYTES
23: 
24:     limit = int(configured)
25:     if limit < 1:
26:         raise ValueError(f"{BUFFER_LIMIT_ENV} must be greater than zero")
27:     return limit
28: 
29: 
30: class Data:
31:     """A byte view returned by Terminal.expect with authority to discard itself."""
32: 
33:     def __init__(self, value, discard_callback=None, *, received_new_data=None):
34:         self.value = bytes(value)
35:         self._discard_callback = discard_callback
36:         self.discarded = False
37:         self.received_new_data = (
38:             bool(self.value) if received_new_data is None else received_new_data
39:         )
40: 
41:     def __bytes__(self):
42:         return self.value
43: 
44:     def __bool__(self):
45:         return bool(self.value)
46: 
47:     def __contains__(self, item):
48:         return item in self.value
49: 
50:     def __len__(self):
51:         return len(self.value)
52: 
53:     def __eq__(self, other):
54:         return self.value == (bytes(other) if isinstance(other, Data) else other)
55: 
56:     def __repr__(self):
57:         return repr(self.value)
58: 
59:     def startswith(self, *args, **kwargs):
60:         return self.value.startswith(*args, **kwargs)
61: 
62:     def decode(self, *args, **kwargs):
63:         return self.value.decode(*args, **kwargs)
64: 
65:     def discard(self, value=None):
66:         discard_value = self.value if value is None else bytes(value)
67:         if not discard_value:
68:             return
69:         if self._discard_callback:
70:             self._discard_callback(discard_value)
71:         self.discarded = True
72: 
73: 
74: class _ByteQueue:
75:     def __init__(self, max_size):
76:         self._max_size = max_size
77:         self._chunks = deque()
78:         self._size = 0
79:         self._closed = False
80:         self._error = None
81:         self._condition = threading.Condition()
82: 
83:     def put(self, data):
84:         offset = 0
85:         while offset < len(data):
86:             with self._condition:
87:                 while not self._closed and self._error is None and self._size >= self._max_size:
88:                     self._condition.wait()
89:                 if self._closed or self._error is not None:
90:                     return
91: 
92:                 available = self._max_size - self._size
93:                 chunk = bytes(data[offset:offset + available])
94:                 self._chunks.append(chunk)
95:                 self._size += len(chunk)
96:                 offset += len(chunk)
97:                 self._condition.notify_all()
98: 
99:     def get(self, timeout=None):
100:         deadline = None if timeout is None else time.monotonic() + timeout
101:         with self._condition:
102:             while not self._chunks and not self._closed and self._error is None:
103:                 if deadline is None:
104:                     self._condition.wait()
105:                     continue
106: 
107:                 remaining = deadline - time.monotonic()
108:                 if remaining <= 0:
109:                     return b""
110:                 self._condition.wait(remaining)
111: 
112:             if self._error is not None:
113:                 raise self._error
114:             if not self._chunks:
115:                 return b""
116: 
117:             data = b"".join(self._chunks)
118:             self._chunks.clear()
119:             self._size = 0
120:             self._condition.notify_all()
121:             return data
122: 
123:     def get_one(self, timeout=None):
124:         deadline = None if timeout is None else time.monotonic() + timeout
125:         with self._condition:
126:             while not self._chunks and not self._closed and self._error is None:
127:                 if deadline is None:
128:                     self._condition.wait()
129:                     continue
130: 
131:                 remaining = deadline - time.monotonic()
132:                 if remaining <= 0:
133:                     return b""
134:                 self._condition.wait(remaining)
135: 
136:             if self._error is not None:
137:                 raise self._error
138:             if not self._chunks:
139:                 return b""
140: 
141:             data = self._chunks.popleft()
142:             self._size -= len(data)
143:             self._condition.notify_all()
144:             return data
145: 
146:     def close(self):
147:         with self._condition:
148:             self._closed = True
149:             self._condition.notify_all()
150: 
151:     def fail(self, error):
152:         with self._condition:
153:             self._error = error
154:             self._condition.notify_all()
155: 
156: 
157: class Terminal:
158:     """Buffered access to the FortiOS serial console."""
159: 
160:     def __init__(self, connection, logger, default_wait="#"):
161:         self._connection = connection
162:         self._logger = logger
163:         self._default_wait = default_wait
164:         self._buffer = bytearray()
165:         self._buffer_limit = terminal_buffer_limit_bytes()
166:         self._read_queue = _ByteQueue(self._buffer_limit)
167:         self._write_queue = _ByteQueue(self._buffer_limit)
168:         self._reader_lock = threading.Lock()
169:         self._stop_reader = None
170:         self._reader = None
171:         self._writer_lock = threading.Lock()
172:         self._writer = None
173:         self._output_suppression_depth = 0
174:         self._output_suppression_context = None
175: 
176:     def write(self, data):
177:         if isinstance(data, str):
178:             data = data.encode()
179:         self._ensure_writer()
180:         self._write_queue.put(data)
181: 
182:     def wait_write(
183:         self,
184:         cmd,
185:         wait="__defaultpattern__",
186:         clean_buffer=False,
187:         hold="",
188:         timeout=None,
189:     ):
190:         if wait:
191:             if wait == "__defaultpattern__":
192:                 wait = self._default_wait
193:             self._logger.info(f"waiting for '{wait}' on serial console")
194:             pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)
195:             _, match, output = self.expect([pattern], timeout)
196: 
197:             while match and hold and hold.encode() in output:
198:                 self._logger.info(
199:                     f"Holding pattern '{hold}' detected, retrying in 10s..."
200:                 )
201:                 self.write(b"\r")
202:                 time.sleep(10)
203:                 _, match, output = self.expect([pattern], timeout)
204: 
205:             if not match:
206:                 self._logger.info(
207:                     f"timed out waiting for '{wait}' on serial console"
208:                 )
209: 
210:         if clean_buffer:
211:             self._buffer.clear()
212: 
213:         self._logger.debug(f"writing to serial console: '{cmd}'")
214:         self.write(f"{cmd}\r")
215: 
216:     def expect(self, regex_list, timeout=None):
217:         """Read until a pattern matches, retaining unmatched data across calls.
218: 
219:         The match ending earliest in the buffered stream wins. Data through that
220:         match is returned and discarded; data after it remains buffered.
221:         On timeout, the entire unmatched buffer is returned for inspection and
222:         stays buffered unless the caller explicitly discards it.
223:         """
224:         self._ensure_reader()
225:         deadline = None if timeout is None else time.monotonic() + timeout
226:         received_new_data = False
227:         result = self._match(regex_list)
228: 
229:         while result is None:
230:             remaining = None if deadline is None else deadline - time.monotonic()
231:             if remaining is not None and remaining <= 0:
232:                 return -1, None, Data(
233:                     self._buffer,
234:                     self._discard_prefix,
235:                     received_new_data=received_new_data,
236:                 )
237: 
238:             data = self._read_queue.get(remaining)
239:             if data:
240:                 self._buffer.extend(data)
241:                 self._enforce_buffer_limit()
242:                 received_new_data = True
243:                 if (
244:                     get_env(RAW_SERIAL_LOG_ENV, "").lower() in ("1", "true", "yes")
245:                     and self._output_suppression_depth == 0
246:                 ):
247:                     self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")
248:                 result = self._match(regex_list)
249:                 continue
250: 
251:             if deadline is not None and time.monotonic() >= deadline:
252:                 return -1, None, Data(
253:                     self._buffer,
254:                     self._discard_prefix,
255:                     received_new_data=received_new_data,
256:                 )
257: 
258:         index, match = result
259:         consumed = bytes(self._buffer[:match.end()])
260:         stable_match = re.search(regex_list[index], consumed)
261:         del self._buffer[:match.end()]
262:         return index, stable_match, Data(consumed)
263: 
264:     def _discard_prefix(self, data):
265:         """Discard bytes that a caller has consumed from the retained buffer."""
266:         if not data:
267:             return
268:         if not self._buffer.startswith(data):
269:             message = "Refusing to discard non-prefix terminal output"
270:             if self._logger.isEnabledFor(TRACE_LEVEL):
271:                 message += f": data={data!r}; buffer={self._buffer!r}"
272:             self._logger.warning(message)
273:             return
274:         del self._buffer[:len(data)]
275: 
276:     def _enforce_buffer_limit(self):
277:         if len(self._buffer) <= self._buffer_limit:
278:             return
279: 
280:         self._logger.error(
281:             "Terminal buffer exceeded %s bytes. Tail: %r",
282:             self._buffer_limit,
283:             bytes(self._buffer[-512:]),
284:         )
285:         raise RuntimeError(
286:             f"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed"
287:         )
288: 
289:     def _ensure_reader(self):
290:         with self._reader_lock:
291:             if self._reader is not None and self._reader.is_alive():
292:                 return
293: 
294:             self._read_queue = _ByteQueue(self._buffer_limit)
295:             self._stop_reader = threading.Event()
296:             self._reader = threading.Thread(
297:                 target=self._read_forever,
298:                 args=(self._stop_reader, self._read_queue),
299:                 name="fortios-terminal-reader",
300:             )
301:             self._reader.daemon = True
302:             self._reader.start()
303: 
304:     def _read_forever(self, stop_reader, read_queue):
305:         while not stop_reader.is_set():
306:             try:
307:                 data = self._connection.read_very_eager()
308:             except Exception as error:
309:                 if not stop_reader.is_set():
310:                     self._logger.exception("Terminal reader failed")
311:                     read_queue.fail(error)
312:                 return
313: 
314:             if data:
315:                 read_queue.put(data)
316:             else:
317:                 stop_reader.wait(READ_POLL_SECONDS)
318: 
319:     def _ensure_writer(self):
320:         with self._writer_lock:
321:             if self._writer is not None and self._writer.is_alive():
322:                 return
323: 
324:             self._write_queue = _ByteQueue(self._buffer_limit)
325:             self._writer = threading.Thread(
326:                 target=self._write_forever,
327:                 args=(self._write_queue,),
328:                 name="fortios-terminal-writer",
329:             )
330:             self._writer.daemon = True
331:             self._writer.start()
332: 
333:     def _write_forever(self, write_queue):
334:         while True:
335:             try:
336:                 data = write_queue.get_one()
337:             except Exception:
338:                 self._logger.exception("Terminal writer failed")
339:                 return
340: 
341:             if not data:
342:                 return
343: 
344:             try:
345:                 self._connection.write(data)
346:             except Exception:
347:                 self._logger.exception("Terminal writer failed")
348:                 return
349: 
350:     def close(self):
351:         with self._reader_lock:
352:             reader = self._reader
353:             stop_reader = self._stop_reader
354:             read_queue = self._read_queue
355:             self._reader = None
356:             self._stop_reader = None
357: 
358:         with self._writer_lock:
359:             writer = self._writer
360:             write_queue = self._write_queue
361:             self._writer = None
362: 
363:         if stop_reader is not None:
364:             stop_reader.set()
365:         read_queue.close()
366:         write_queue.close()
367:         if writer is not None:
368:             writer.join(1)
369:         self._buffer.clear()
370:         self._connection.close()
371:         if reader is not None:
372:             reader.join(1)
373: 
374:     @contextmanager
375:     def suppress_output(self):
376:         if self._output_suppression_depth == 0:
377:             self._output_suppression_context = self._connection.suppress_output()
378:             self._output_suppression_context.__enter__()
379:         self._output_suppression_depth += 1
380:         try:
381:             yield
382:         finally:
383:             self._output_suppression_depth -= 1
384:             if self._output_suppression_depth == 0:
385:                 try:
386:                     self._output_suppression_context.__exit__(None, None, None)
387:                 finally:
388:                     self._output_suppression_context = None
389: 
390:     def _match(self, regex_list):
391:         winner = None
392:         for index, pattern in enumerate(regex_list):
393:             match = re.search(pattern, self._buffer)
394:             if match is None:
395:                 continue
396:             if winner is None or match.end() < winner[1].end():
397:                 winner = index, match
398:         return winner

(End of file - total 398 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d15e63001ICQvQfOSUWiGQW",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d14ce4001k1NWsz8TzXeS62",
  "callID": "call_3428c2e3a7ff43ca89c486e0",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/terminal.py"
    },
    "output": "<path>/source/head/fortinet/common/terminal.py</path>\n<type>file</type>\n<content>\n1: import cmd\n2: import logging\n3: import re\n4: import threading\n5: import time\n6: from collections import deque\n7: from contextlib import contextmanager\n8: \n9: from .common import TRACE_LEVEL\n10: from .env import get_env\n11: \n12: \n13: DEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024\n14: BUFFER_LIMIT_ENV = \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\"\n15: READ_POLL_SECONDS = 0.001\n16: RAW_SERIAL_LOG_ENV = \"FOS_LOG_RAW_SERIAL\"\n17: \n18: \n19: def terminal_buffer_limit_bytes():\n20:     configured = get_env(BUFFER_LIMIT_ENV)\n21:     if not configured:\n22:         return DEFAULT_BUFFER_LIMIT_BYTES\n23: \n24:     limit = int(configured)\n25:     if limit < 1:\n26:         raise ValueError(f\"{BUFFER_LIMIT_ENV} must be greater than zero\")\n27:     return limit\n28: \n29: \n30: class Data:\n31:     \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n32: \n33:     def __init__(self, value, discard_callback=None, *, received_new_data=None):\n34:         self.value = bytes(value)\n35:         self._discard_callback = discard_callback\n36:         self.discarded = False\n37:         self.received_new_data = (\n38:             bool(self.value) if received_new_data is None else received_new_data\n39:         )\n40: \n41:     def __bytes__(self):\n42:         return self.value\n43: \n44:     def __bool__(self):\n45:         return bool(self.value)\n46: \n47:     def __contains__(self, item):\n48:         return item in self.value\n49: \n50:     def __len__(self):\n51:         return len(self.value)\n52: \n53:     def __eq__(self, other):\n54:         return self.value == (bytes(other) if isinstance(other, Data) else other)\n55: \n56:     def __repr__(self):\n57:         return repr(self.value)\n58: \n59:     def startswith(self, *args, **kwargs):\n60:         return self.value.startswith(*args, **kwargs)\n61: \n62:     def decode(self, *args, **kwargs):\n63:         return self.value.decode(*args, **kwargs)\n64: \n65:     def discard(self, value=None):\n66:         discard_value = self.value if value is None else bytes(value)\n67:         if not discard_value:\n68:             return\n69:         if self._discard_callback:\n70:             self._discard_callback(discard_value)\n71:         self.discarded = True\n72: \n73: \n74: class _ByteQueue:\n75:     def __init__(self, max_size):\n76:         self._max_size = max_size\n77:         self._chunks = deque()\n78:         self._size = 0\n79:         self._closed = False\n80:         self._error = None\n81:         self._condition = threading.Condition()\n82: \n83:     def put(self, data):\n84:         offset = 0\n85:         while offset < len(data):\n86:             with self._condition:\n87:                 while not self._closed and self._error is None and self._size >= self._max_size:\n88:                     self._condition.wait()\n89:                 if self._closed or self._error is not None:\n90:                     return\n91: \n92:                 available = self._max_size - self._size\n93:                 chunk = bytes(data[offset:offset + available])\n94:                 self._chunks.append(chunk)\n95:                 self._size += len(chunk)\n96:                 offset += len(chunk)\n97:                 self._condition.notify_all()\n98: \n99:     def get(self, timeout=None):\n100:         deadline = None if timeout is None else time.monotonic() + timeout\n101:         with self._condition:\n102:             while not self._chunks and not self._closed and self._error is None:\n103:                 if deadline is None:\n104:                     self._condition.wait()\n105:                     continue\n106: \n107:                 remaining = deadline - time.monotonic()\n108:                 if remaining <= 0:\n109:                     return b\"\"\n110:                 self._condition.wait(remaining)\n111: \n112:             if self._error is not None:\n113:                 raise self._error\n114:             if not self._chunks:\n115:                 return b\"\"\n116: \n117:             data = b\"\".join(self._chunks)\n118:             self._chunks.clear()\n119:             self._size = 0\n120:             self._condition.notify_all()\n121:             return data\n122: \n123:     def get_one(self, timeout=None):\n124:         deadline = None if timeout is None else time.monotonic() + timeout\n125:         with self._condition:\n126:             while not self._chunks and not self._closed and self._error is None:\n127:                 if deadline is None:\n128:                     self._condition.wait()\n129:                     continue\n130: \n131:                 remaining = deadline - time.monotonic()\n132:                 if remaining <= 0:\n133:                     return b\"\"\n134:                 self._condition.wait(remaining)\n135: \n136:             if self._error is not None:\n137:                 raise self._error\n138:             if not self._chunks:\n139:                 return b\"\"\n140: \n141:             data = self._chunks.popleft()\n142:             self._size -= len(data)\n143:             self._condition.notify_all()\n144:             return data\n145: \n146:     def close(self):\n147:         with self._condition:\n148:             self._closed = True\n149:             self._condition.notify_all()\n150: \n151:     def fail(self, error):\n152:         with self._condition:\n153:             self._error = error\n154:             self._condition.notify_all()\n155: \n156: \n157: class Terminal:\n158:     \"\"\"Buffered access to the FortiOS serial console.\"\"\"\n159: \n160:     def __init__(self, connection, logger, default_wait=\"#\"):\n161:         self._connection = connection\n162:         self._logger = logger\n163:         self._default_wait = default_wait\n164:         self._buffer = bytearray()\n165:         self._buffer_limit = terminal_buffer_limit_bytes()\n166:         self._read_queue = _ByteQueue(self._buffer_limit)\n167:         self._write_queue = _ByteQueue(self._buffer_limit)\n168:         self._reader_lock = threading.Lock()\n169:         self._stop_reader = None\n170:         self._reader = None\n171:         self._writer_lock = threading.Lock()\n172:         self._writer = None\n173:         self._output_suppression_depth = 0\n174:         self._output_suppression_context = None\n175: \n176:     def write(self, data):\n177:         if isinstance(data, str):\n178:             data = data.encode()\n179:         self._ensure_writer()\n180:         self._write_queue.put(data)\n181: \n182:     def wait_write(\n183:         self,\n184:         cmd,\n185:         wait=\"__defaultpattern__\",\n186:         clean_buffer=False,\n187:         hold=\"\",\n188:         timeout=None,\n189:     ):\n190:         if wait:\n191:             if wait == \"__defaultpattern__\":\n192:                 wait = self._default_wait\n193:             self._logger.info(f\"waiting for '{wait}' on serial console\")\n194:             pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)\n195:             _, match, output = self.expect([pattern], timeout)\n196: \n197:             while match and hold and hold.encode() in output:\n198:                 self._logger.info(\n199:                     f\"Holding pattern '{hold}' detected, retrying in 10s...\"\n200:                 )\n201:                 self.write(b\"\\r\")\n202:                 time.sleep(10)\n203:                 _, match, output = self.expect([pattern], timeout)\n204: \n205:             if not match:\n206:                 self._logger.info(\n207:                     f\"timed out waiting for '{wait}' on serial console\"\n208:                 )\n209: \n210:         if clean_buffer:\n211:             self._buffer.clear()\n212: \n213:         self._logger.debug(f\"writing to serial console: '{cmd}'\")\n214:         self.write(f\"{cmd}\\r\")\n215: \n216:     def expect(self, regex_list, timeout=None):\n217:         \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n218: \n219:         The match ending earliest in the buffered stream wins. Data through that\n220:         match is returned and discarded; data after it remains buffered.\n221:         On timeout, the entire unmatched buffer is returned for inspection and\n222:         stays buffered unless the caller explicitly discards it.\n223:         \"\"\"\n224:         self._ensure_reader()\n225:         deadline = None if timeout is None else time.monotonic() + timeout\n226:         received_new_data = False\n227:         result = self._match(regex_list)\n228: \n229:         while result is None:\n230:             remaining = None if deadline is None else deadline - time.monotonic()\n231:             if remaining is not None and remaining <= 0:\n232:                 return -1, None, Data(\n233:                     self._buffer,\n234:                     self._discard_prefix,\n235:                     received_new_data=received_new_data,\n236:                 )\n237: \n238:             data = self._read_queue.get(remaining)\n239:             if data:\n240:                 self._buffer.extend(data)\n241:                 self._enforce_buffer_limit()\n242:                 received_new_data = True\n243:                 if (\n244:                     get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n245:                     and self._output_suppression_depth == 0\n246:                 ):\n247:                     self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n248:                 result = self._match(regex_list)\n249:                 continue\n250: \n251:             if deadline is not None and time.monotonic() >= deadline:\n252:                 return -1, None, Data(\n253:                     self._buffer,\n254:                     self._discard_prefix,\n255:                     received_new_data=received_new_data,\n256:                 )\n257: \n258:         index, match = result\n259:         consumed = bytes(self._buffer[:match.end()])\n260:         stable_match = re.search(regex_list[index], consumed)\n261:         del self._buffer[:match.end()]\n262:         return index, stable_match, Data(consumed)\n263: \n264:     def _discard_prefix(self, data):\n265:         \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n266:         if not data:\n267:             return\n268:         if not self._buffer.startswith(data):\n269:             message = \"Refusing to discard non-prefix terminal output\"\n270:             if self._logger.isEnabledFor(TRACE_LEVEL):\n271:                 message += f\": data={data!r}; buffer={self._buffer!r}\"\n272:             self._logger.warning(message)\n273:             return\n274:         del self._buffer[:len(data)]\n275: \n276:     def _enforce_buffer_limit(self):\n277:         if len(self._buffer) <= self._buffer_limit:\n278:             return\n279: \n280:         self._logger.error(\n281:             \"Terminal buffer exceeded %s bytes. Tail: %r\",\n282:             self._buffer_limit,\n283:             bytes(self._buffer[-512:]),\n284:         )\n285:         raise RuntimeError(\n286:             f\"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed\"\n287:         )\n288: \n289:     def _ensure_reader(self):\n290:         with self._reader_lock:\n291:             if self._reader is not None and self._reader.is_alive():\n292:                 return\n293: \n294:             self._read_queue = _ByteQueue(self._buffer_limit)\n295:             self._stop_reader = threading.Event()\n296:             self._reader = threading.Thread(\n297:                 target=self._read_forever,\n298:                 args=(self._stop_reader, self._read_queue),\n299:                 name=\"fortios-terminal-reader\",\n300:             )\n301:             self._reader.daemon = True\n302:             self._reader.start()\n303: \n304:     def _read_forever(self, stop_reader, read_queue):\n305:         while not stop_reader.is_set():\n306:             try:\n307:                 data = self._connection.read_very_eager()\n308:             except Exception as error:\n309:                 if not stop_reader.is_set():\n310:                     self._logger.exception(\"Terminal reader failed\")\n311:                     read_queue.fail(error)\n312:                 return\n313: \n314:             if data:\n315:                 read_queue.put(data)\n316:             else:\n317:                 stop_reader.wait(READ_POLL_SECONDS)\n318: \n319:     def _ensure_writer(self):\n320:         with self._writer_lock:\n321:             if self._writer is not None and self._writer.is_alive():\n322:                 return\n323: \n324:             self._write_queue = _ByteQueue(self._buffer_limit)\n325:             self._writer = threading.Thread(\n326:                 target=self._write_forever,\n327:                 args=(self._write_queue,),\n328:                 name=\"fortios-terminal-writer\",\n329:             )\n330:             self._writer.daemon = True\n331:             self._writer.start()\n332: \n333:     def _write_forever(self, write_queue):\n334:         while True:\n335:             try:\n336:                 data = write_queue.get_one()\n337:             except Exception:\n338:                 self._logger.exception(\"Terminal writer failed\")\n339:                 return\n340: \n341:             if not data:\n342:                 return\n343: \n344:             try:\n345:                 self._connection.write(data)\n346:             except Exception:\n347:                 self._logger.exception(\"Terminal writer failed\")\n348:                 return\n349: \n350:     def close(self):\n351:         with self._reader_lock:\n352:             reader = self._reader\n353:             stop_reader = self._stop_reader\n354:             read_queue = self._read_queue\n355:             self._reader = None\n356:             self._stop_reader = None\n357: \n358:         with self._writer_lock:\n359:             writer = self._writer\n360:             write_queue = self._write_queue\n361:             self._writer = None\n362: \n363:         if stop_reader is not None:\n364:             stop_reader.set()\n365:         read_queue.close()\n366:         write_queue.close()\n367:         if writer is not None:\n368:             writer.join(1)\n369:         self._buffer.clear()\n370:         self._connection.close()\n371:         if reader is not None:\n372:             reader.join(1)\n373: \n374:     @contextmanager\n375:     def suppress_output(self):\n376:         if self._output_suppression_depth == 0:\n377:             self._output_suppression_context = self._connection.suppress_output()\n378:             self._output_suppression_context.__enter__()\n379:         self._output_suppression_depth += 1\n380:         try:\n381:             yield\n382:         finally:\n383:             self._output_suppression_depth -= 1\n384:             if self._output_suppression_depth == 0:\n385:                 try:\n386:                     self._output_suppression_context.__exit__(None, None, None)\n387:                 finally:\n388:                     self._output_suppression_context = None\n389: \n390:     def _match(self, regex_list):\n391:         winner = None\n392:         for index, pattern in enumerate(regex_list):\n393:             match = re.search(pattern, self._buffer)\n394:             if match is None:\n395:                 continue\n396:             if winner is None or match.end() < winner[1].end():\n397:                 winner = index, match\n398:         return winner\n\n(End of file - total 398 lines)\n</content>",
    "title": "source/head/fortinet/common/terminal.py",
    "metadata": {
      "preview": "import cmd\nimport logging\nimport re\nimport threading\nimport time\nfrom collections import deque\nfrom contextlib import contextmanager\n\nfrom .common import TRACE_LEVEL\nfrom .env import get_env\n\n\nDEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024\nBUFFER_LIMIT_ENV = \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\"\nREAD_POLL_SECONDS = 0.001\nRAW_SERIAL_LOG_ENV = \"FOS_LOG_RAW_SERIAL\"\n\n\ndef terminal_buffer_limit_bytes():\n    configured = get_env(BUFFER_LIMIT_ENV)",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/terminal.py",
        "text": "import cmd\nimport logging\nimport re\nimport threading\nimport time\nfrom collections import deque\nfrom contextlib import contextmanager\n\nfrom .common import TRACE_LEVEL\nfrom .env import get_env\n\n\nDEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024\nBUFFER_LIMIT_ENV = \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\"\nREAD_POLL_SECONDS = 0.001\nRAW_SERIAL_LOG_ENV = \"FOS_LOG_RAW_SERIAL\"\n\n\ndef terminal_buffer_limit_bytes():\n    configured = get_env(BUFFER_LIMIT_ENV)\n    if not configured:\n        return DEFAULT_BUFFER_LIMIT_BYTES\n\n    limit = int(configured)\n    if limit < 1:\n        raise ValueError(f\"{BUFFER_LIMIT_ENV} must be greater than zero\")\n    return limit\n\n\nclass Data:\n    \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n\n    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n        self.value = bytes(value)\n        self._discard_callback = discard_callback\n        self.discarded = False\n        self.received_new_data = (\n            bool(self.value) if received_new_data is None else received_new_data\n        )\n\n    def __bytes__(self):\n        return self.value\n\n    def __bool__(self):\n        return bool(self.value)\n\n    def __contains__(self, item):\n        return item in self.value\n\n    def __len__(self):\n        return len(self.value)\n\n    def __eq__(self, other):\n        return self.value == (bytes(other) if isinstance(other, Data) else other)\n\n    def __repr__(self):\n        return repr(self.value)\n\n    def startswith(self, *args, **kwargs):\n        return self.value.startswith(*args, **kwargs)\n\n    def decode(self, *args, **kwargs):\n        return self.value.decode(*args, **kwargs)\n\n    def discard(self, value=None):\n        discard_value = self.value if value is None else bytes(value)\n        if not discard_value:\n            return\n        if self._discard_callback:\n            self._discard_callback(discard_value)\n        self.discarded = True\n\n\nclass _ByteQueue:\n    def __init__(self, max_size):\n        self._max_size = max_size\n        self._chunks = deque()\n        self._size = 0\n        self._closed = False\n        self._error = None\n        self._condition = threading.Condition()\n\n    def put(self, data):\n        offset = 0\n        while offset < len(data):\n            with self._condition:\n                while not self._closed and self._error is None and self._size >= self._max_size:\n                    self._condition.wait()\n                if self._closed or self._error is not None:\n                    return\n\n                available = self._max_size - self._size\n                chunk = bytes(data[offset:offset + available])\n                self._chunks.append(chunk)\n                self._size += len(chunk)\n                offset += len(chunk)\n                self._condition.notify_all()\n\n    def get(self, timeout=None):\n        deadline = None if timeout is None else time.monotonic() + timeout\n        with self._condition:\n            while not self._chunks and not self._closed and self._error is None:\n                if deadline is None:\n                    self._condition.wait()\n                    continue\n\n                remaining = deadline - time.monotonic()\n                if remaining <= 0:\n                    return b\"\"\n                self._condition.wait(remaining)\n\n            if self._error is not None:\n                raise self._error\n            if not self._chunks:\n                return b\"\"\n\n            data = b\"\".join(self._chunks)\n            self._chunks.clear()\n            self._size = 0\n            self._condition.notify_all()\n            return data\n\n    def get_one(self, timeout=None):\n        deadline = None if timeout is None else time.monotonic() + timeout\n        with self._condition:\n            while not self._chunks and not self._closed and self._error is None:\n                if deadline is None:\n                    self._condition.wait()\n                    continue\n\n                remaining = deadline - time.monotonic()\n                if remaining <= 0:\n                    return b\"\"\n                self._condition.wait(remaining)\n\n            if self._error is not None:\n                raise self._error\n            if not self._chunks:\n                return b\"\"\n\n            data = self._chunks.popleft()\n            self._size -= len(data)\n            self._condition.notify_all()\n            return data\n\n    def close(self):\n        with self._condition:\n            self._closed = True\n            self._condition.notify_all()\n\n    def fail(self, error):\n        with self._condition:\n            self._error = error\n            self._condition.notify_all()\n\n\nclass Terminal:\n    \"\"\"Buffered access to the FortiOS serial console.\"\"\"\n\n    def __init__(self, connection, logger, default_wait=\"#\"):\n        self._connection = connection\n        self._logger = logger\n        self._default_wait = default_wait\n        self._buffer = bytearray()\n        self._buffer_limit = terminal_buffer_limit_bytes()\n        self._read_queue = _ByteQueue(self._buffer_limit)\n        self._write_queue = _ByteQueue(self._buffer_limit)\n        self._reader_lock = threading.Lock()\n        self._stop_reader = None\n        self._reader = None\n        self._writer_lock = threading.Lock()\n        self._writer = None\n        self._output_suppression_depth = 0\n        self._output_suppression_context = None\n\n    def write(self, data):\n        if isinstance(data, str):\n            data = data.encode()\n        self._ensure_writer()\n        self._write_queue.put(data)\n\n    def wait_write(\n        self,\n        cmd,\n        wait=\"__defaultpattern__\",\n        clean_buffer=False,\n        hold=\"\",\n        timeout=None,\n    ):\n        if wait:\n            if wait == \"__defaultpattern__\":\n                wait = self._default_wait\n            self._logger.info(f\"waiting for '{wait}' on serial console\")\n            pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)\n            _, match, output = self.expect([pattern], timeout)\n\n            while match and hold and hold.encode() in output:\n                self._logger.info(\n                    f\"Holding pattern '{hold}' detected, retrying in 10s...\"\n                )\n                self.write(b\"\\r\")\n                time.sleep(10)\n                _, match, output = self.expect([pattern], timeout)\n\n            if not match:\n                self._logger.info(\n                    f\"timed out waiting for '{wait}' on serial console\"\n                )\n\n        if clean_buffer:\n            self._buffer.clear()\n\n        self._logger.debug(f\"writing to serial console: '{cmd}'\")\n        self.write(f\"{cmd}\\r\")\n\n    def expect(self, regex_list, timeout=None):\n        \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n\n        The match ending earliest in the buffered stream wins. Data through that\n        match is returned and discarded; data after it remains buffered.\n        On timeout, the entire unmatched buffer is returned for inspection and\n        stays buffered unless the caller explicitly discards it.\n        \"\"\"\n        self._ensure_reader()\n        deadline = None if timeout is None else time.monotonic() + timeout\n        received_new_data = False\n        result = self._match(regex_list)\n\n        while result is None:\n            remaining = None if deadline is None else deadline - time.monotonic()\n            if remaining is not None and remaining <= 0:\n                return -1, None, Data(\n                    self._buffer,\n                    self._discard_prefix,\n                    received_new_data=received_new_data,\n                )\n\n            data = self._read_queue.get(remaining)\n            if data:\n                self._buffer.extend(data)\n                self._enforce_buffer_limit()\n                received_new_data = True\n                if (\n                    get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n                    and self._output_suppression_depth == 0\n                ):\n                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n                result = self._match(regex_list)\n                continue\n\n            if deadline is not None and time.monotonic() >= deadline:\n                return -1, None, Data(\n                    self._buffer,\n                    self._discard_prefix,\n                    received_new_data=received_new_data,\n                )\n\n        index, match = result\n        consumed = bytes(self._buffer[:match.end()])\n        stable_match = re.search(regex_list[index], consumed)\n        del self._buffer[:match.end()]\n        return index, stable_match, Data(consumed)\n\n    def _discard_prefix(self, data):\n        \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n        if not data:\n            return\n        if not self._buffer.startswith(data):\n            message = \"Refusing to discard non-prefix terminal output\"\n            if self._logger.isEnabledFor(TRACE_LEVEL):\n                message += f\": data={data!r}; buffer={self._buffer!r}\"\n            self._logger.warning(message)\n            return\n        del self._buffer[:len(data)]\n\n    def _enforce_buffer_limit(self):\n        if len(self._buffer) <= self._buffer_limit:\n            return\n\n        self._logger.error(\n            \"Terminal buffer exceeded %s bytes. Tail: %r\",\n            self._buffer_limit,\n            bytes(self._buffer[-512:]),\n        )\n        raise RuntimeError(\n            f\"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed\"\n        )\n\n    def _ensure_reader(self):\n        with self._reader_lock:\n            if self._reader is not None and self._reader.is_alive():\n                return\n\n            self._read_queue = _ByteQueue(self._buffer_limit)\n            self._stop_reader = threading.Event()\n            self._reader = threading.Thread(\n                target=self._read_forever,\n                args=(self._stop_reader, self._read_queue),\n                name=\"fortios-terminal-reader\",\n            )\n            self._reader.daemon = True\n            self._reader.start()\n\n    def _read_forever(self, stop_reader, read_queue):\n        while not stop_reader.is_set():\n            try:\n                data = self._connection.read_very_eager()\n            except Exception as error:\n                if not stop_reader.is_set():\n                    self._logger.exception(\"Terminal reader failed\")\n                    read_queue.fail(error)\n                return\n\n            if data:\n                read_queue.put(data)\n            else:\n                stop_reader.wait(READ_POLL_SECONDS)\n\n    def _ensure_writer(self):\n        with self._writer_lock:\n            if self._writer is not None and self._writer.is_alive():\n                return\n\n            self._write_queue = _ByteQueue(self._buffer_limit)\n            self._writer = threading.Thread(\n                target=self._write_forever,\n                args=(self._write_queue,),\n                name=\"fortios-terminal-writer\",\n            )\n            self._writer.daemon = True\n            self._writer.start()\n\n    def _write_forever(self, write_queue):\n        while True:\n            try:\n                data = write_queue.get_one()\n            except Exception:\n                self._logger.exception(\"Terminal writer failed\")\n                return\n\n            if not data:\n                return\n\n            try:\n                self._connection.write(data)\n            except Exception:\n                self._logger.exception(\"Terminal writer failed\")\n                return\n\n    def close(self):\n        with self._reader_lock:\n            reader = self._reader\n            stop_reader = self._stop_reader\n            read_queue = self._read_queue\n            self._reader = None\n            self._stop_reader = None\n\n        with self._writer_lock:\n            writer = self._writer\n            write_queue = self._write_queue\n            self._writer = None\n\n        if stop_reader is not None:\n            stop_reader.set()\n        read_queue.close()\n        write_queue.close()\n        if writer is not None:\n            writer.join(1)\n        self._buffer.clear()\n        self._connection.close()\n        if reader is not None:\n            reader.join(1)\n\n    @contextmanager\n    def suppress_output(self):\n        if self._output_suppression_depth == 0:\n            self._output_suppression_context = self._connection.suppress_output()\n            self._output_suppression_context.__enter__()\n        self._output_suppression_depth += 1\n        try:\n            yield\n        finally:\n            self._output_suppression_depth -= 1\n            if self._output_suppression_depth == 0:\n                try:\n                    self._output_suppression_context.__exit__(None, None, None)\n                finally:\n                    self._output_suppression_context = None\n\n    def _match(self, regex_list):\n        winner = None\n        for index, pattern in enumerate(regex_list):\n            match = re.search(pattern, self._buffer)\n            if match is None:\n                continue\n            if winner is None or match.end() < winner[1].end():\n                winner = index, match\n        return winner",
        "lineStart": 1,
        "lineEnd": 398,
        "totalLines": 398,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716215402,
      "end": 1793716215412
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_cli_driver.py"
}

Output

<path>/source/head/fortinet/common/fos_cli_driver.py</path>
<type>file</type>
<content>
1: import logging
2: import re
3: import time
4: from .common import (
5:     FOSCliState,
6:     FOS_CLI_STATE_PATTERNS,
7:     BOOTSTRAP_HOSTNAME_REGEX,
8:     PROMPT_CONTEXT_REGEX,
9:     TRACE_LEVEL,
10: )
11: 
12: 
13: PROCESS_SPIN_SECONDS = 10
14: EXPECT_TIMEOUT_SECONDS = 1
15: UNKNOWN_STALL_SECONDS = 30
16: UNKNOWN_STALL_NEWLINE_LIMIT = 3
17: 
18: 
19: class KernelPanicError(RuntimeError):
20:     """Raised when the guest kernel reports a panic on the serial console."""
21: 
22: 
23: class FOSCliDriver:
24:     """Owns serial reads and delegates command dispatch to the commander."""
25: 
26:     def __init__(
27:         self,
28:         terminal,
29:         commander,
30:         credentials,
31:         logger,
32:         bootstrap_password,
33:         activate_blank_credentials,
34:         activate_bootstrap_credentials,
35:         allow_credential_recovery=False,
36:     ):
37:         self._terminal = terminal
38:         self._commander = commander
39:         self._logger = logger
40:         self._state_patterns = FOS_CLI_STATE_PATTERNS.copy()
41:         self._last_known_state = FOSCliState.UNKNOWN
42:         self._current_state = FOSCliState.UNKNOWN
43:         self._last_logged_state = None
44:         self._idle_spins = 0
45:         self._credentials = credentials
46:         self._bootstrap_password = bootstrap_password
47:         self._activate_blank_credentials = activate_blank_credentials
48:         self._activate_bootstrap_credentials = activate_bootstrap_credentials
49:         self._allow_credential_recovery = allow_credential_recovery
50:         self._recovery_credentials = None
51:         self._recovery_attempted = False
52:         self._use_recovery_credentials = False
53:         self._blank_fallback_available = True
54:         self._send_blank_password = False
55:         self._initial_login_complete = False
56:         self._awaiting_login_acceptance = False
57:         self._credential_recovery_pending = False
58:         self._pending_bootstrap_activation = False
59:         self._unknown_started_at = None
60:         self._unknown_newlines = 0
61:         self._state_handlers = {
62:             FOSCliState.PROVIDE_USERNAME: self._provide_username,
63:             FOSCliState.PROVIDE_PASSWORD: self._provide_password,
64:             FOSCliState.CURRENT_PASSWORD: self._provide_current_password,
65:             FOSCliState.CHANGE_PASSWORD: self._provide_new_password,
66:             FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,
67:             FOSCliState.MORE_PROMPT: self._continue_pager,
68:             FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,
69:             FOSCliState.CMD_PROMPT: self._command_prompt,
70:             FOSCliState.CMD_PROMPT_ECHO: None,
71:             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,
72:             FOSCliState.LIC_FAIL: self._license_failed,
73:             FOSCliState.TN_TIMEOUT: self._timeout,
74:             FOSCliState.KERNEL_PANIC: self._kernel_panic,
75:             FOSCliState.UNKNOWN: self._unknown,
76:         }
77: 
78:     @property
79:     def state_patterns(self):
80:         return self._state_patterns
81: 
82:     @property
83:     def ready(self):
84:         return self._commander.ready
85: 
86:     def remember_current_credentials(self):
87:         """Keep the last accepted credentials for a failed password transition."""
88:         if self._recovery_credentials is not None or self._recovery_attempted:
89:             return
90:         self._recovery_credentials = (
91:             self._credentials.username,
92:             self._credentials.password,
93:         )
94:         self._recovery_attempted = False
95: 
96:     @property
97:     def at_command_prompt(self):
98:         """Whether the most recent console event left FortiOS at a CLI prompt."""
99:         return self._current_state == FOSCliState.CMD_PROMPT or (
100:             self._current_state == FOSCliState.TN_TIMEOUT
101:             and self._last_known_state == FOSCliState.CMD_PROMPT
102:         )
103: 
104:     def process_state(self):
105:         spin_start = time.time()
106:         while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:
107:             state, output, matched = self._next_state()
108:             self._current_state = state
109:             if output and not matched:
110:                 self._commander.on_output(output)
111:                 if state == FOSCliState.UNKNOWN:
112:                     self._note_unknown_output()
113:                 output = type(output)(b"")
114:             if state.value < FOSCliState.UNKNOWN.value:
115:                 self._idle_spins = 0
116:                 self._last_known_state = state
117:                 self._clear_unknown_stall()
118:                 self._log_state(state)
119:             self._process_state(state, output)
120: 
121:     def _log_state(self, state):
122:         if state == FOSCliState.MULTILINE_PROMPT:
123:             return
124:         if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:
125:             return
126:         self._last_logged_state = state
127:         self._logger.debug(f"ST: {state.name}")
128: 
129:     def _process_state(self, state, output):
130:         """Handle a CLI state and then let the commander observe it.
131: 
132:         A password confirmation can be followed immediately by a command
133:         prompt, without ``Welcome!``.  Apply that credential transition
134:         before the commander dispatches the command associated with the
135:         prompt.
136:         """
137:         if state == FOSCliState.CMD_PROMPT:
138:             self._handle_state(state)
139:         if state == FOSCliState.CMD_PROMPT_ECHO:
140:             self._commander.on_prompt_echo(output)
141:         else:
142:             self._commander.on_state(state, output)
143:         if state != FOSCliState.CMD_PROMPT:
144:             self._handle_state(state)
145:         if state == FOSCliState.CMD_PROMPT:
146:             self._commander.tick()
147:         elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:
148:             self._commander.tick()
149:             self._commander.on_idle_prompt()
150: 
151:     def _next_state(self):
152:         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)
153:         if match:
154:             return FOSCliState(index), output, True
155:         # A timeout exposes retained bytes too. Only fresh input should reset
156:         # the unknown-output stall timer; an unchanged buffer is still idle.
157:         state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT
158:         return state, output, False
159: 
160:     def _handle_state(self, state):
161:         handler = self._state_handlers.get(state)
162:         if handler:
163:             try:
164:                 handler()
165:             except Exception:
166:                 self._logger.exception("CLI state handler failed for %s", state.name)
167:                 raise
168: 
169:     def _provide_username(self):
170:         username = self._credentials.username
171:         if self._use_recovery_credentials and self._recovery_credentials is not None:
172:             username = self._recovery_credentials[0]
173:         self._awaiting_login_acceptance = True
174:         self._respond(FOSCliState.PROVIDE_USERNAME, username)
175: 
176:     def _provide_password(self):
177:         if self._send_blank_password:
178:             # The initial blank-password fallback is consumed as soon as it is
179:             # sent. Later credential recovery is managed separately.
180:             self._send_blank_password = False
181:             self._blank_fallback_available = False
182:             self._activate_blank_credentials()
183:             self._respond(FOSCliState.PROVIDE_PASSWORD, b"")
184:             return
185:         if self._use_recovery_credentials and self._recovery_credentials is not None:
186:             self._respond(
187:                 FOSCliState.PROVIDE_PASSWORD,
188:                 self._recovery_credentials[1],
189:             )
190:             return
191:         self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)
192: 
193:     def _provide_current_password(self):
194:         self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)
195: 
196:     def _provide_new_password(self):
197:         self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)
198: 
199:     def _confirm_new_password(self):
200:         self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)
201:         # Do not update active credentials until FortiOS accepts the
202:         # confirmation. A rejected confirmation leaves the active password
203:         # unchanged so that subsequent prompts use the right value.
204:         self._pending_bootstrap_activation = True
205: 
206:     def _continue_pager(self):
207:         self._terminal.write(b" ")
208: 
209:     def _credential_accepted(self):
210:         self._accept_login()
211: 
212:     def _accept_login(self):
213:         self._initial_login_complete = True
214:         self._awaiting_login_acceptance = False
215:         recovered = (
216:             self._use_recovery_credentials
217:             and self._recovery_credentials is not None
218:         )
219:         if recovered:
220:             self._use_recovery_credentials = False
221:             self._recovery_attempted = False
222:             if not self._credential_recovery_pending:
223:                 self._commander.record_feature_error(
224:                     "admin-credentials",
225:                     "desired credentials were rejected; resumed with the previous credentials "
226:                     "while keeping the desired credentials for later logins",
227:                 )
228:             self._credential_recovery_pending = True
229:         elif self._recovery_credentials is not None:
230:             self._recovery_attempted = False
231:             if self._credential_recovery_pending:
232:                 self._commander.resolve_feature_error(
233:                     "admin-credentials",
234:                     "the desired credentials authenticated successfully",
235:                 )
236:                 self._credential_recovery_pending = False
237:         self._activate_pending_bootstrap_credentials()
238: 
239:     def _command_prompt(self):
240:         """Accept password confirmation on versions that skip ``Welcome!``."""
241:         if self._awaiting_login_acceptance:
242:             self._accept_login()
243:         else:
244:             self._initial_login_complete = True
245:             self._activate_pending_bootstrap_credentials()
246: 
247:     def _activate_pending_bootstrap_credentials(self):
248:         if self._pending_bootstrap_activation:
249:             self._activate_bootstrap_credentials()
250:             self._pending_bootstrap_activation = False
251: 
252:     @staticmethod
253:     def _license_failed():
254:         # SetLicense inspects the buffered command output when FortiOS returns
255:         # to a prompt. Raising here would interrupt the driver at LIC_FAIL,
256:         # before best-effort bootstrap can safely skip the feature.
257:         return None
258: 
259:     def _timeout(self):
260:         self._idle_spins += 1
261:         self._recover_unknown_stall()
262: 
263:     def _unknown(self):
264:         if self._last_known_state == FOSCliState.REBOOTING:
265:             self._idle_spins += 1
266: 
267:     @staticmethod
268:     def _kernel_panic():
269:         raise KernelPanicError("Kernel panic detected on serial console")
270: 
271:     def _note_unknown_output(self):
272:         self._unknown_started_at = time.monotonic()
273: 
274:     def _recover_unknown_stall(self):
275:         if self._unknown_started_at is None:
276:             return
277:         if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:
278:             return
279:         if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:
280:             raise RuntimeError("CLI remained in unknown state")
281:         self._unknown_newlines += 1
282:         self._unknown_started_at = time.monotonic()
283:         self._logger.warning(
284:             "CLI stuck in unknown state; sending newline "
285:             f"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})"
286:         )
287:         self._terminal.write(b"\r")
288: 
289:     def _clear_unknown_stall(self):
290:         self._unknown_started_at = None
291:         self._unknown_newlines = 0
292: 
293:     def set_prompt_patterns(self, name_pattern):
294:         if isinstance(name_pattern, str):
295:             name_pattern = re.escape(name_pattern.encode())
296:         self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb"(?m)^[ \t]*" + name_pattern + rb"[ \t]+login:[ \t]*"
297:         self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*\r?$"
298:         self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*[^\r\n]+(?:\r?\n)?"
299: 
300:     def _credential_rejected(self):
301:         # A rejected interaction cannot establish the newly selected
302:         # bootstrap password.  Do not activate it on a later unrelated
303:         # acceptance or prompt.
304:         self._pending_bootstrap_activation = False
305:         if not self._initial_login_complete and self._blank_fallback_available:
306:             self._send_blank_password = True
307:             return
308:         if (
309:             self._allow_credential_recovery
310:             and self._recovery_credentials is not None
311:             and not self._recovery_attempted
312:         ):
313:             self._recovery_attempted = True
314:             self._use_recovery_credentials = True
315:             self._logger.warning(
316:                 "Credentials were rejected; retrying with the previously accepted credentials"
317:             )
318:             return
319:         raise RuntimeError("Credential rejected")
320: 
321:     def _respond(self, state, response):
322:         """Write an interactive response to the CLI."""
323:         if isinstance(response, str):
324:             response = response.encode()
325:         self._logger.log(
326:             TRACE_LEVEL,
327:             "Responding to CLI state %s with '%s'",
328:             state.name,
329:             response,
330:         )
331:         self._terminal.write(bytes(response) + b"\r")

(End of file - total 331 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d15eac001fDgro12xKWuBNg",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d14ce4001k1NWsz8TzXeS62",
  "callID": "call_4152cdaf8d1f4bbc9e574dd6",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_cli_driver.py"
    },
    "output": "<path>/source/head/fortinet/common/fos_cli_driver.py</path>\n<type>file</type>\n<content>\n1: import logging\n2: import re\n3: import time\n4: from .common import (\n5:     FOSCliState,\n6:     FOS_CLI_STATE_PATTERNS,\n7:     BOOTSTRAP_HOSTNAME_REGEX,\n8:     PROMPT_CONTEXT_REGEX,\n9:     TRACE_LEVEL,\n10: )\n11: \n12: \n13: PROCESS_SPIN_SECONDS = 10\n14: EXPECT_TIMEOUT_SECONDS = 1\n15: UNKNOWN_STALL_SECONDS = 30\n16: UNKNOWN_STALL_NEWLINE_LIMIT = 3\n17: \n18: \n19: class KernelPanicError(RuntimeError):\n20:     \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n21: \n22: \n23: class FOSCliDriver:\n24:     \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n25: \n26:     def __init__(\n27:         self,\n28:         terminal,\n29:         commander,\n30:         credentials,\n31:         logger,\n32:         bootstrap_password,\n33:         activate_blank_credentials,\n34:         activate_bootstrap_credentials,\n35:         allow_credential_recovery=False,\n36:     ):\n37:         self._terminal = terminal\n38:         self._commander = commander\n39:         self._logger = logger\n40:         self._state_patterns = FOS_CLI_STATE_PATTERNS.copy()\n41:         self._last_known_state = FOSCliState.UNKNOWN\n42:         self._current_state = FOSCliState.UNKNOWN\n43:         self._last_logged_state = None\n44:         self._idle_spins = 0\n45:         self._credentials = credentials\n46:         self._bootstrap_password = bootstrap_password\n47:         self._activate_blank_credentials = activate_blank_credentials\n48:         self._activate_bootstrap_credentials = activate_bootstrap_credentials\n49:         self._allow_credential_recovery = allow_credential_recovery\n50:         self._recovery_credentials = None\n51:         self._recovery_attempted = False\n52:         self._use_recovery_credentials = False\n53:         self._blank_fallback_available = True\n54:         self._send_blank_password = False\n55:         self._initial_login_complete = False\n56:         self._awaiting_login_acceptance = False\n57:         self._credential_recovery_pending = False\n58:         self._pending_bootstrap_activation = False\n59:         self._unknown_started_at = None\n60:         self._unknown_newlines = 0\n61:         self._state_handlers = {\n62:             FOSCliState.PROVIDE_USERNAME: self._provide_username,\n63:             FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n64:             FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n65:             FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n66:             FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n67:             FOSCliState.MORE_PROMPT: self._continue_pager,\n68:             FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n69:             FOSCliState.CMD_PROMPT: self._command_prompt,\n70:             FOSCliState.CMD_PROMPT_ECHO: None,\n71:             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n72:             FOSCliState.LIC_FAIL: self._license_failed,\n73:             FOSCliState.TN_TIMEOUT: self._timeout,\n74:             FOSCliState.KERNEL_PANIC: self._kernel_panic,\n75:             FOSCliState.UNKNOWN: self._unknown,\n76:         }\n77: \n78:     @property\n79:     def state_patterns(self):\n80:         return self._state_patterns\n81: \n82:     @property\n83:     def ready(self):\n84:         return self._commander.ready\n85: \n86:     def remember_current_credentials(self):\n87:         \"\"\"Keep the last accepted credentials for a failed password transition.\"\"\"\n88:         if self._recovery_credentials is not None or self._recovery_attempted:\n89:             return\n90:         self._recovery_credentials = (\n91:             self._credentials.username,\n92:             self._credentials.password,\n93:         )\n94:         self._recovery_attempted = False\n95: \n96:     @property\n97:     def at_command_prompt(self):\n98:         \"\"\"Whether the most recent console event left FortiOS at a CLI prompt.\"\"\"\n99:         return self._current_state == FOSCliState.CMD_PROMPT or (\n100:             self._current_state == FOSCliState.TN_TIMEOUT\n101:             and self._last_known_state == FOSCliState.CMD_PROMPT\n102:         )\n103: \n104:     def process_state(self):\n105:         spin_start = time.time()\n106:         while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:\n107:             state, output, matched = self._next_state()\n108:             self._current_state = state\n109:             if output and not matched:\n110:                 self._commander.on_output(output)\n111:                 if state == FOSCliState.UNKNOWN:\n112:                     self._note_unknown_output()\n113:                 output = type(output)(b\"\")\n114:             if state.value < FOSCliState.UNKNOWN.value:\n115:                 self._idle_spins = 0\n116:                 self._last_known_state = state\n117:                 self._clear_unknown_stall()\n118:                 self._log_state(state)\n119:             self._process_state(state, output)\n120: \n121:     def _log_state(self, state):\n122:         if state == FOSCliState.MULTILINE_PROMPT:\n123:             return\n124:         if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:\n125:             return\n126:         self._last_logged_state = state\n127:         self._logger.debug(f\"ST: {state.name}\")\n128: \n129:     def _process_state(self, state, output):\n130:         \"\"\"Handle a CLI state and then let the commander observe it.\n131: \n132:         A password confirmation can be followed immediately by a command\n133:         prompt, without ``Welcome!``.  Apply that credential transition\n134:         before the commander dispatches the command associated with the\n135:         prompt.\n136:         \"\"\"\n137:         if state == FOSCliState.CMD_PROMPT:\n138:             self._handle_state(state)\n139:         if state == FOSCliState.CMD_PROMPT_ECHO:\n140:             self._commander.on_prompt_echo(output)\n141:         else:\n142:             self._commander.on_state(state, output)\n143:         if state != FOSCliState.CMD_PROMPT:\n144:             self._handle_state(state)\n145:         if state == FOSCliState.CMD_PROMPT:\n146:             self._commander.tick()\n147:         elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:\n148:             self._commander.tick()\n149:             self._commander.on_idle_prompt()\n150: \n151:     def _next_state(self):\n152:         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n153:         if match:\n154:             return FOSCliState(index), output, True\n155:         # A timeout exposes retained bytes too. Only fresh input should reset\n156:         # the unknown-output stall timer; an unchanged buffer is still idle.\n157:         state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n158:         return state, output, False\n159: \n160:     def _handle_state(self, state):\n161:         handler = self._state_handlers.get(state)\n162:         if handler:\n163:             try:\n164:                 handler()\n165:             except Exception:\n166:                 self._logger.exception(\"CLI state handler failed for %s\", state.name)\n167:                 raise\n168: \n169:     def _provide_username(self):\n170:         username = self._credentials.username\n171:         if self._use_recovery_credentials and self._recovery_credentials is not None:\n172:             username = self._recovery_credentials[0]\n173:         self._awaiting_login_acceptance = True\n174:         self._respond(FOSCliState.PROVIDE_USERNAME, username)\n175: \n176:     def _provide_password(self):\n177:         if self._send_blank_password:\n178:             # The initial blank-password fallback is consumed as soon as it is\n179:             # sent. Later credential recovery is managed separately.\n180:             self._send_blank_password = False\n181:             self._blank_fallback_available = False\n182:             self._activate_blank_credentials()\n183:             self._respond(FOSCliState.PROVIDE_PASSWORD, b\"\")\n184:             return\n185:         if self._use_recovery_credentials and self._recovery_credentials is not None:\n186:             self._respond(\n187:                 FOSCliState.PROVIDE_PASSWORD,\n188:                 self._recovery_credentials[1],\n189:             )\n190:             return\n191:         self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)\n192: \n193:     def _provide_current_password(self):\n194:         self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)\n195: \n196:     def _provide_new_password(self):\n197:         self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)\n198: \n199:     def _confirm_new_password(self):\n200:         self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)\n201:         # Do not update active credentials until FortiOS accepts the\n202:         # confirmation. A rejected confirmation leaves the active password\n203:         # unchanged so that subsequent prompts use the right value.\n204:         self._pending_bootstrap_activation = True\n205: \n206:     def _continue_pager(self):\n207:         self._terminal.write(b\" \")\n208: \n209:     def _credential_accepted(self):\n210:         self._accept_login()\n211: \n212:     def _accept_login(self):\n213:         self._initial_login_complete = True\n214:         self._awaiting_login_acceptance = False\n215:         recovered = (\n216:             self._use_recovery_credentials\n217:             and self._recovery_credentials is not None\n218:         )\n219:         if recovered:\n220:             self._use_recovery_credentials = False\n221:             self._recovery_attempted = False\n222:             if not self._credential_recovery_pending:\n223:                 self._commander.record_feature_error(\n224:                     \"admin-credentials\",\n225:                     \"desired credentials were rejected; resumed with the previous credentials \"\n226:                     \"while keeping the desired credentials for later logins\",\n227:                 )\n228:             self._credential_recovery_pending = True\n229:         elif self._recovery_credentials is not None:\n230:             self._recovery_attempted = False\n231:             if self._credential_recovery_pending:\n232:                 self._commander.resolve_feature_error(\n233:                     \"admin-credentials\",\n234:                     \"the desired credentials authenticated successfully\",\n235:                 )\n236:                 self._credential_recovery_pending = False\n237:         self._activate_pending_bootstrap_credentials()\n238: \n239:     def _command_prompt(self):\n240:         \"\"\"Accept password confirmation on versions that skip ``Welcome!``.\"\"\"\n241:         if self._awaiting_login_acceptance:\n242:             self._accept_login()\n243:         else:\n244:             self._initial_login_complete = True\n245:             self._activate_pending_bootstrap_credentials()\n246: \n247:     def _activate_pending_bootstrap_credentials(self):\n248:         if self._pending_bootstrap_activation:\n249:             self._activate_bootstrap_credentials()\n250:             self._pending_bootstrap_activation = False\n251: \n252:     @staticmethod\n253:     def _license_failed():\n254:         # SetLicense inspects the buffered command output when FortiOS returns\n255:         # to a prompt. Raising here would interrupt the driver at LIC_FAIL,\n256:         # before best-effort bootstrap can safely skip the feature.\n257:         return None\n258: \n259:     def _timeout(self):\n260:         self._idle_spins += 1\n261:         self._recover_unknown_stall()\n262: \n263:     def _unknown(self):\n264:         if self._last_known_state == FOSCliState.REBOOTING:\n265:             self._idle_spins += 1\n266: \n267:     @staticmethod\n268:     def _kernel_panic():\n269:         raise KernelPanicError(\"Kernel panic detected on serial console\")\n270: \n271:     def _note_unknown_output(self):\n272:         self._unknown_started_at = time.monotonic()\n273: \n274:     def _recover_unknown_stall(self):\n275:         if self._unknown_started_at is None:\n276:             return\n277:         if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:\n278:             return\n279:         if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:\n280:             raise RuntimeError(\"CLI remained in unknown state\")\n281:         self._unknown_newlines += 1\n282:         self._unknown_started_at = time.monotonic()\n283:         self._logger.warning(\n284:             \"CLI stuck in unknown state; sending newline \"\n285:             f\"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})\"\n286:         )\n287:         self._terminal.write(b\"\\r\")\n288: \n289:     def _clear_unknown_stall(self):\n290:         self._unknown_started_at = None\n291:         self._unknown_newlines = 0\n292: \n293:     def set_prompt_patterns(self, name_pattern):\n294:         if isinstance(name_pattern, str):\n295:             name_pattern = re.escape(name_pattern.encode())\n296:         self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb\"(?m)^[ \\t]*\" + name_pattern + rb\"[ \\t]+login:[ \\t]*\"\n297:         self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n298:         self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n299: \n300:     def _credential_rejected(self):\n301:         # A rejected interaction cannot establish the newly selected\n302:         # bootstrap password.  Do not activate it on a later unrelated\n303:         # acceptance or prompt.\n304:         self._pending_bootstrap_activation = False\n305:         if not self._initial_login_complete and self._blank_fallback_available:\n306:             self._send_blank_password = True\n307:             return\n308:         if (\n309:             self._allow_credential_recovery\n310:             and self._recovery_credentials is not None\n311:             and not self._recovery_attempted\n312:         ):\n313:             self._recovery_attempted = True\n314:             self._use_recovery_credentials = True\n315:             self._logger.warning(\n316:                 \"Credentials were rejected; retrying with the previously accepted credentials\"\n317:             )\n318:             return\n319:         raise RuntimeError(\"Credential rejected\")\n320: \n321:     def _respond(self, state, response):\n322:         \"\"\"Write an interactive response to the CLI.\"\"\"\n323:         if isinstance(response, str):\n324:             response = response.encode()\n325:         self._logger.log(\n326:             TRACE_LEVEL,\n327:             \"Responding to CLI state %s with '%s'\",\n328:             state.name,\n329:             response,\n330:         )\n331:         self._terminal.write(bytes(response) + b\"\\r\")\n\n(End of file - total 331 lines)\n</content>",
    "title": "source/head/fortinet/common/fos_cli_driver.py",
    "metadata": {
      "preview": "import logging\nimport re\nimport time\nfrom .common import (\n    FOSCliState,\n    FOS_CLI_STATE_PATTERNS,\n    BOOTSTRAP_HOSTNAME_REGEX,\n    PROMPT_CONTEXT_REGEX,\n    TRACE_LEVEL,\n)\n\n\nPROCESS_SPIN_SECONDS = 10\nEXPECT_TIMEOUT_SECONDS = 1\nUNKNOWN_STALL_SECONDS = 30\nUNKNOWN_STALL_NEWLINE_LIMIT = 3\n\n\nclass KernelPanicError(RuntimeError):\n    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_cli_driver.py",
        "text": "import logging\nimport re\nimport time\nfrom .common import (\n    FOSCliState,\n    FOS_CLI_STATE_PATTERNS,\n    BOOTSTRAP_HOSTNAME_REGEX,\n    PROMPT_CONTEXT_REGEX,\n    TRACE_LEVEL,\n)\n\n\nPROCESS_SPIN_SECONDS = 10\nEXPECT_TIMEOUT_SECONDS = 1\nUNKNOWN_STALL_SECONDS = 30\nUNKNOWN_STALL_NEWLINE_LIMIT = 3\n\n\nclass KernelPanicError(RuntimeError):\n    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n\n\nclass FOSCliDriver:\n    \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n\n    def __init__(\n        self,\n        terminal,\n        commander,\n        credentials,\n        logger,\n        bootstrap_password,\n        activate_blank_credentials,\n        activate_bootstrap_credentials,\n        allow_credential_recovery=False,\n    ):\n        self._terminal = terminal\n        self._commander = commander\n        self._logger = logger\n        self._state_patterns = FOS_CLI_STATE_PATTERNS.copy()\n        self._last_known_state = FOSCliState.UNKNOWN\n        self._current_state = FOSCliState.UNKNOWN\n        self._last_logged_state = None\n        self._idle_spins = 0\n        self._credentials = credentials\n        self._bootstrap_password = bootstrap_password\n        self._activate_blank_credentials = activate_blank_credentials\n        self._activate_bootstrap_credentials = activate_bootstrap_credentials\n        self._allow_credential_recovery = allow_credential_recovery\n        self._recovery_credentials = None\n        self._recovery_attempted = False\n        self._use_recovery_credentials = False\n        self._blank_fallback_available = True\n        self._send_blank_password = False\n        self._initial_login_complete = False\n        self._awaiting_login_acceptance = False\n        self._credential_recovery_pending = False\n        self._pending_bootstrap_activation = False\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n        self._state_handlers = {\n            FOSCliState.PROVIDE_USERNAME: self._provide_username,\n            FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n            FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n            FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n            FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n            FOSCliState.MORE_PROMPT: self._continue_pager,\n            FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n            FOSCliState.CMD_PROMPT: self._command_prompt,\n            FOSCliState.CMD_PROMPT_ECHO: None,\n            FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n            FOSCliState.LIC_FAIL: self._license_failed,\n            FOSCliState.TN_TIMEOUT: self._timeout,\n            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n            FOSCliState.UNKNOWN: self._unknown,\n        }\n\n    @property\n    def state_patterns(self):\n        return self._state_patterns\n\n    @property\n    def ready(self):\n        return self._commander.ready\n\n    def remember_current_credentials(self):\n        \"\"\"Keep the last accepted credentials for a failed password transition.\"\"\"\n        if self._recovery_credentials is not None or self._recovery_attempted:\n            return\n        self._recovery_credentials = (\n            self._credentials.username,\n            self._credentials.password,\n        )\n        self._recovery_attempted = False\n\n    @property\n    def at_command_prompt(self):\n        \"\"\"Whether the most recent console event left FortiOS at a CLI prompt.\"\"\"\n        return self._current_state == FOSCliState.CMD_PROMPT or (\n            self._current_state == FOSCliState.TN_TIMEOUT\n            and self._last_known_state == FOSCliState.CMD_PROMPT\n        )\n\n    def process_state(self):\n        spin_start = time.time()\n        while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:\n            state, output, matched = self._next_state()\n            self._current_state = state\n            if output and not matched:\n                self._commander.on_output(output)\n                if state == FOSCliState.UNKNOWN:\n                    self._note_unknown_output()\n                output = type(output)(b\"\")\n            if state.value < FOSCliState.UNKNOWN.value:\n                self._idle_spins = 0\n                self._last_known_state = state\n                self._clear_unknown_stall()\n                self._log_state(state)\n            self._process_state(state, output)\n\n    def _log_state(self, state):\n        if state == FOSCliState.MULTILINE_PROMPT:\n            return\n        if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:\n            return\n        self._last_logged_state = state\n        self._logger.debug(f\"ST: {state.name}\")\n\n    def _process_state(self, state, output):\n        \"\"\"Handle a CLI state and then let the commander observe it.\n\n        A password confirmation can be followed immediately by a command\n        prompt, without ``Welcome!``.  Apply that credential transition\n        before the commander dispatches the command associated with the\n        prompt.\n        \"\"\"\n        if state == FOSCliState.CMD_PROMPT:\n            self._handle_state(state)\n        if state == FOSCliState.CMD_PROMPT_ECHO:\n            self._commander.on_prompt_echo(output)\n        else:\n            self._commander.on_state(state, output)\n        if state != FOSCliState.CMD_PROMPT:\n            self._handle_state(state)\n        if state == FOSCliState.CMD_PROMPT:\n            self._commander.tick()\n        elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:\n            self._commander.tick()\n            self._commander.on_idle_prompt()\n\n    def _next_state(self):\n        index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n        if match:\n            return FOSCliState(index), output, True\n        # A timeout exposes retained bytes too. Only fresh input should reset\n        # the unknown-output stall timer; an unchanged buffer is still idle.\n        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n        return state, output, False\n\n    def _handle_state(self, state):\n        handler = self._state_handlers.get(state)\n        if handler:\n            try:\n                handler()\n            except Exception:\n                self._logger.exception(\"CLI state handler failed for %s\", state.name)\n                raise\n\n    def _provide_username(self):\n        username = self._credentials.username\n        if self._use_recovery_credentials and self._recovery_credentials is not None:\n            username = self._recovery_credentials[0]\n        self._awaiting_login_acceptance = True\n        self._respond(FOSCliState.PROVIDE_USERNAME, username)\n\n    def _provide_password(self):\n        if self._send_blank_password:\n            # The initial blank-password fallback is consumed as soon as it is\n            # sent. Later credential recovery is managed separately.\n            self._send_blank_password = False\n            self._blank_fallback_available = False\n            self._activate_blank_credentials()\n            self._respond(FOSCliState.PROVIDE_PASSWORD, b\"\")\n            return\n        if self._use_recovery_credentials and self._recovery_credentials is not None:\n            self._respond(\n                FOSCliState.PROVIDE_PASSWORD,\n                self._recovery_credentials[1],\n            )\n            return\n        self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)\n\n    def _provide_current_password(self):\n        self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)\n\n    def _provide_new_password(self):\n        self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)\n\n    def _confirm_new_password(self):\n        self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)\n        # Do not update active credentials until FortiOS accepts the\n        # confirmation. A rejected confirmation leaves the active password\n        # unchanged so that subsequent prompts use the right value.\n        self._pending_bootstrap_activation = True\n\n    def _continue_pager(self):\n        self._terminal.write(b\" \")\n\n    def _credential_accepted(self):\n        self._accept_login()\n\n    def _accept_login(self):\n        self._initial_login_complete = True\n        self._awaiting_login_acceptance = False\n        recovered = (\n            self._use_recovery_credentials\n            and self._recovery_credentials is not None\n        )\n        if recovered:\n            self._use_recovery_credentials = False\n            self._recovery_attempted = False\n            if not self._credential_recovery_pending:\n                self._commander.record_feature_error(\n                    \"admin-credentials\",\n                    \"desired credentials were rejected; resumed with the previous credentials \"\n                    \"while keeping the desired credentials for later logins\",\n                )\n            self._credential_recovery_pending = True\n        elif self._recovery_credentials is not None:\n            self._recovery_attempted = False\n            if self._credential_recovery_pending:\n                self._commander.resolve_feature_error(\n                    \"admin-credentials\",\n                    \"the desired credentials authenticated successfully\",\n                )\n                self._credential_recovery_pending = False\n        self._activate_pending_bootstrap_credentials()\n\n    def _command_prompt(self):\n        \"\"\"Accept password confirmation on versions that skip ``Welcome!``.\"\"\"\n        if self._awaiting_login_acceptance:\n            self._accept_login()\n        else:\n            self._initial_login_complete = True\n            self._activate_pending_bootstrap_credentials()\n\n    def _activate_pending_bootstrap_credentials(self):\n        if self._pending_bootstrap_activation:\n            self._activate_bootstrap_credentials()\n            self._pending_bootstrap_activation = False\n\n    @staticmethod\n    def _license_failed():\n        # SetLicense inspects the buffered command output when FortiOS returns\n        # to a prompt. Raising here would interrupt the driver at LIC_FAIL,\n        # before best-effort bootstrap can safely skip the feature.\n        return None\n\n    def _timeout(self):\n        self._idle_spins += 1\n        self._recover_unknown_stall()\n\n    def _unknown(self):\n        if self._last_known_state == FOSCliState.REBOOTING:\n            self._idle_spins += 1\n\n    @staticmethod\n    def _kernel_panic():\n        raise KernelPanicError(\"Kernel panic detected on serial console\")\n\n    def _note_unknown_output(self):\n        self._unknown_started_at = time.monotonic()\n\n    def _recover_unknown_stall(self):\n        if self._unknown_started_at is None:\n            return\n        if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:\n            return\n        if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:\n            raise RuntimeError(\"CLI remained in unknown state\")\n        self._unknown_newlines += 1\n        self._unknown_started_at = time.monotonic()\n        self._logger.warning(\n            \"CLI stuck in unknown state; sending newline \"\n            f\"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})\"\n        )\n        self._terminal.write(b\"\\r\")\n\n    def _clear_unknown_stall(self):\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n\n    def set_prompt_patterns(self, name_pattern):\n        if isinstance(name_pattern, str):\n            name_pattern = re.escape(name_pattern.encode())\n        self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb\"(?m)^[ \\t]*\" + name_pattern + rb\"[ \\t]+login:[ \\t]*\"\n        self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n        self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n\n    def _credential_rejected(self):\n        # A rejected interaction cannot establish the newly selected\n        # bootstrap password.  Do not activate it on a later unrelated\n        # acceptance or prompt.\n        self._pending_bootstrap_activation = False\n        if not self._initial_login_complete and self._blank_fallback_available:\n            self._send_blank_password = True\n            return\n        if (\n            self._allow_credential_recovery\n            and self._recovery_credentials is not None\n            and not self._recovery_attempted\n        ):\n            self._recovery_attempted = True\n            self._use_recovery_credentials = True\n            self._logger.warning(\n                \"Credentials were rejected; retrying with the previously accepted credentials\"\n            )\n            return\n        raise RuntimeError(\"Credential rejected\")\n\n    def _respond(self, state, response):\n        \"\"\"Write an interactive response to the CLI.\"\"\"\n        if isinstance(response, str):\n            response = response.encode()\n        self._logger.log(\n            TRACE_LEVEL,\n            \"Responding to CLI state %s with '%s'\",\n            state.name,\n            response,\n        )\n        self._terminal.write(bytes(response) + b\"\\r\")",
        "lineStart": 1,
        "lineEnd": 331,
        "totalLines": 331,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716215476,
      "end": 1793716215490
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d15ec40017T3DMlEaP66W9y",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d14ce4001k1NWsz8TzXeS62",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 64111,
    "input": 64073,
    "output": 37,
    "reasoning": 1,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d14ce4001k1NWsz8TzXeS62",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716210916,
    "completed": 1793716215494
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 64111,
    "input": 64073,
    "output": 37,
    "reasoning": 1,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 8
step-start
{
  "type": "step-start",
  "id": "prt_1a1d169ef001Hqbm8ATaW33JFs",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d15ec9001CVKHxoy6epRdK5"
}
Reasoning
Interesting notes so far:

1. In `terminal.py`, `RAW_SERIAL_LOG_ENV = "FOS_LOG_RAW_SERIAL"` — but the test test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias expects env names `FTNT_LOG_RAW_SERIAL` and `FOS_LOG_RAW_SERIAL`. Let me check `env.py` — it wasn't changed in this diff, but maybe env.py provides aliasing. Actually env.py is in head files (1523 bytes, 48 lines). Let me read env.py. If env.py maps FOS_* to FTNT_* aliases, then `get_env(RAW_SERIAL_LOG_ENV...)` might handle both. But the diff shows `self._logger.log(TRACE_LEVEL, ...)` changed from TRACE_LEVEL-1 to TRACE_LEVEL. The test asserts TRACE_LEVEL. Need to check env.py for aliasing.

2. `terminal_buffer_limit_bytes` uses `BUFFER_LIMIT_ENV = "FOS_TERMINAL_BUFFER_LIMIT_BYTES"`, and the test now expects `FTNT_TERMINAL_BUFFER_LIMIT_BYTES` to take precedence (64 over 32). If env.py handles aliases via get_env, then BUFFER_LIMIT_ENV constant would need to be the FTNT name for precedence. But the head terminal.py shows BUFFER_LIMIT_ENV = "FOS_TERMINAL_BUFFER_LIMIT_BYTES". Hmm, but the error message in terminal_buffer_limit_bytes says `{BUFFER_LIMIT_ENV} must be greater than zero`. The test patches FTNT to 64 and FOS to 32, clear=True, and expects 64. If get_env("FOS_TERMINAL_BUFFER_LIMIT_BYTES") just reads that name, it would return "32" → limit 32, failing the test. Unless env.py's get_env normalizes names FOS_ → FTNT_ with FTNT taking precedence. Let me read env.py.

Note: env.py is not in the changed list, but the manifest lists it as head file. Wait — actually is env.py part of the PR? The changed list has 18 paths; env.py is not among them. But the test changes reference FTNT_* env names. If env.py already handles aliases (pre-existing), fine. But wait — maybe this snapshot's env.py is from the head and already includes aliases? The PR adds tests asserting behavior of terminal_buffer_limit_bytes with FTNT precedence. If env.py already handles this, fine. Let me check.

Also the RAW_SERIAL_LOG_ENV test: `terminal.expect([b"matched"], timeout=0.1)` with logger MagicMock. The terminal_with_data helper — need to see it. The test asserts `_logger.log.assert_called_once_with(TRACE_LEVEL, "buffer: bytearray(b'matched')")`. In head terminal.py, the log call is `self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")` where `self._buffer` is a bytearray, so f-string of bytearray gives "bytearray(b'matched')". OK matches.

But wait — for both env names, the test loops over both names. If env.py get_env supports aliases such that both FOS_LOG_RAW_SERIAL and FTNT_LOG_RAW_SERIAL work, fine.

Let me now read env.py, launch.py, startup_config.py, pki.py (diff portion), and the tests.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/env.py"
}

Output

<path>/source/head/fortinet/common/env.py</path>
<type>file</type>
<content>
1: """Environment variable compatibility helpers for Fortinet launchers."""
2: 
3: import os
4: 
5: 
6: def _candidate_names(name, aliases=(), legacy_aliases=()):
7:     """Yield preferred aliases, the FTNT spelling, then the original name."""
8:     seen = set()
9:     for candidate in aliases:
10:         if candidate not in seen:
11:             seen.add(candidate)
12:             yield candidate
13: 
14:     if name.startswith("FOS_"):
15:         ftnt_name = "FTNT_" + name[len("FOS_"):]
16:         if ftnt_name not in seen:
17:             seen.add(ftnt_name)
18:             yield ftnt_name
19: 
20:     if name not in seen:
21:         seen.add(name)
22:         yield name
23: 
24:     for candidate in legacy_aliases:
25:         if candidate not in seen:
26:             seen.add(candidate)
27:             yield candidate
28: 
29: 
30: def get_env(name, default=None, *, aliases=(), legacy_aliases=()):
31:     """Read an environment variable, preferring its FTNT spelling.
32: 
33:     ``aliases`` are checked first for renamed variables. ``legacy_aliases``
34:     are checked only after the canonical name to preserve older misspellings
35:     without allowing them to override a current spelling.
36:     """
37:     for candidate in _candidate_names(name, aliases, legacy_aliases):
38:         if candidate in os.environ:
39:             return os.environ[candidate]
40:     return default
41: 
42: 
43: def has_env(name, *, aliases=(), legacy_aliases=()):
44:     """Return whether any supported spelling is present in the environment."""
45:     return any(
46:         candidate in os.environ
47:         for candidate in _candidate_names(name, aliases, legacy_aliases)
48:     )

(End of file - total 48 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d1820e001G5rqUFOmAiJpV9",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d15ec9001CVKHxoy6epRdK5",
  "callID": "call_86308a057f794c9db8110e74",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/env.py"
    },
    "output": "<path>/source/head/fortinet/common/env.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Environment variable compatibility helpers for Fortinet launchers.\"\"\"\n2: \n3: import os\n4: \n5: \n6: def _candidate_names(name, aliases=(), legacy_aliases=()):\n7:     \"\"\"Yield preferred aliases, the FTNT spelling, then the original name.\"\"\"\n8:     seen = set()\n9:     for candidate in aliases:\n10:         if candidate not in seen:\n11:             seen.add(candidate)\n12:             yield candidate\n13: \n14:     if name.startswith(\"FOS_\"):\n15:         ftnt_name = \"FTNT_\" + name[len(\"FOS_\"):]\n16:         if ftnt_name not in seen:\n17:             seen.add(ftnt_name)\n18:             yield ftnt_name\n19: \n20:     if name not in seen:\n21:         seen.add(name)\n22:         yield name\n23: \n24:     for candidate in legacy_aliases:\n25:         if candidate not in seen:\n26:             seen.add(candidate)\n27:             yield candidate\n28: \n29: \n30: def get_env(name, default=None, *, aliases=(), legacy_aliases=()):\n31:     \"\"\"Read an environment variable, preferring its FTNT spelling.\n32: \n33:     ``aliases`` are checked first for renamed variables. ``legacy_aliases``\n34:     are checked only after the canonical name to preserve older misspellings\n35:     without allowing them to override a current spelling.\n36:     \"\"\"\n37:     for candidate in _candidate_names(name, aliases, legacy_aliases):\n38:         if candidate in os.environ:\n39:             return os.environ[candidate]\n40:     return default\n41: \n42: \n43: def has_env(name, *, aliases=(), legacy_aliases=()):\n44:     \"\"\"Return whether any supported spelling is present in the environment.\"\"\"\n45:     return any(\n46:         candidate in os.environ\n47:         for candidate in _candidate_names(name, aliases, legacy_aliases)\n48:     )\n\n(End of file - total 48 lines)\n</content>",
    "title": "source/head/fortinet/common/env.py",
    "metadata": {
      "preview": "\"\"\"Environment variable compatibility helpers for Fortinet launchers.\"\"\"\n\nimport os\n\n\ndef _candidate_names(name, aliases=(), legacy_aliases=()):\n    \"\"\"Yield preferred aliases, the FTNT spelling, then the original name.\"\"\"\n    seen = set()\n    for candidate in aliases:\n        if candidate not in seen:\n            seen.add(candidate)\n            yield candidate\n\n    if name.startswith(\"FOS_\"):\n        ftnt_name = \"FTNT_\" + name[len(\"FOS_\"):]\n        if ftnt_name not in seen:\n            seen.add(ftnt_name)\n            yield ftnt_name\n\n    if name not in seen:",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/env.py",
        "text": "\"\"\"Environment variable compatibility helpers for Fortinet launchers.\"\"\"\n\nimport os\n\n\ndef _candidate_names(name, aliases=(), legacy_aliases=()):\n    \"\"\"Yield preferred aliases, the FTNT spelling, then the original name.\"\"\"\n    seen = set()\n    for candidate in aliases:\n        if candidate not in seen:\n            seen.add(candidate)\n            yield candidate\n\n    if name.startswith(\"FOS_\"):\n        ftnt_name = \"FTNT_\" + name[len(\"FOS_\"):]\n        if ftnt_name not in seen:\n            seen.add(ftnt_name)\n            yield ftnt_name\n\n    if name not in seen:\n        seen.add(name)\n        yield name\n\n    for candidate in legacy_aliases:\n        if candidate not in seen:\n            seen.add(candidate)\n            yield candidate\n\n\ndef get_env(name, default=None, *, aliases=(), legacy_aliases=()):\n    \"\"\"Read an environment variable, preferring its FTNT spelling.\n\n    ``aliases`` are checked first for renamed variables. ``legacy_aliases``\n    are checked only after the canonical name to preserve older misspellings\n    without allowing them to override a current spelling.\n    \"\"\"\n    for candidate in _candidate_names(name, aliases, legacy_aliases):\n        if candidate in os.environ:\n            return os.environ[candidate]\n    return default\n\n\ndef has_env(name, *, aliases=(), legacy_aliases=()):\n    \"\"\"Return whether any supported spelling is present in the environment.\"\"\"\n    return any(\n        candidate in os.environ\n        for candidate in _candidate_names(name, aliases, legacy_aliases)\n    )",
        "lineStart": 1,
        "lineEnd": 48,
        "totalLines": 48,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716224531,
      "end": 1793716224538
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/startup_config.py"
}

Output

<path>/source/head/fortinet/common/features/startup_config.py</path>
<type>file</type>
<content>
1: """User startup configuration feature."""
2: 
3: import os
4: 
5: from ..cli_commands import ConfigBlock, EditBlock
6: from ..env import has_env
7: from .base import StaticFeature
8: 
9: 
10: class ApplyStartupConfig(StaticFeature):
11:     def __init__(self, vm, commander):
12:         path = "/config/startup-config.cfg"
13:         blocks = parse_startup_config(path) if os.path.exists(path) else []
14:         blocks = filter_startup_config_blocks(blocks, commander.logger)
15:         super().__init__(vm, commander, "startup-config", blocks)
16: 
17: 
18: def filter_startup_config_blocks(blocks, logger):
19:     """Skip startup DNS configuration that conflicts with FortiGuard hook DNS."""
20:     if not (
21:         has_env("FOS_FORTIGUARD_HOOKS")
22:         and (
23:             has_env("FOS_MGMT_DNS_PRIMARY", aliases=("FTNT_DNS_PRIMARY",))
24:             or has_env(
25:                 "FOS_MGMT_DNS_SECONDARY",
26:                 aliases=("FTNT_DNS_SECONDARY",),
27:                 legacy_aliases=("FTNT_MGMG_DNS_SECONDARY", "FOS_MGMG_DNS_SECONDARY"),
28:             )
29:             or has_env("FTNT_DNS_PROTOCOL")
30:         )
31:     ):
32:         return blocks
33: 
34:     filtered = [
35:         block
36:         for block in blocks
37:         if not (isinstance(block, ConfigBlock) and block.value == "system dns")
38:     ]
39:     if len(filtered) != len(blocks):
40:         logger.warning(
41:             "Skipping startup config block 'config system dns' because "
42:             "FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY, "
43:             "FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL"
44:         )
45:     return filtered
46: 
47: 
48: def _startup_config_commands(config):
49:     """Yield logical CLI commands while retaining quoted newlines verbatim."""
50:     pending = []
51:     quote = None
52:     start_line = None
53:     for number, raw_line in enumerate(config, start=1):
54:         # Text mode normalizes file line endings. Only remove the delimiter;
55:         # whitespace and comment/scope-looking lines inside quotes are data.
56:         line = raw_line.removesuffix("\n")
57:         if not pending:
58:             line = line.lstrip()
59:             if not line or line.startswith("#"):
60:                 continue
61:             start_line = number
62: 
63:         escaped = False
64:         for character in line:
65:             if escaped:
66:                 escaped = False
67:             elif character == "\\":
68:                 escaped = True
69:             elif character == quote:
70:                 quote = None
71:             elif quote is None and character in {"'", '"'}:
72:                 quote = character
73: 
74:         if quote is not None or escaped:
75:             pending.append(line)
76:             continue
77:         pending.append(line.rstrip())
78:         yield "\n".join(pending)
79:         pending.clear()
80: 
81:     if pending:
82:         reason = "unterminated quoted string" if quote else "unfinished line continuation"
83:         raise ValueError(
84:             f"Startup config malformed. {reason} starting on line {start_line}."
85:         )
86: 
87: 
88: def parse_startup_config(path):
89:     roots = []
90:     stack = []
91:     with open(path) as config:
92:         for line in _startup_config_commands(config):
93:             if line.startswith("config "):
94:                 node = ConfigBlock(line[7:])
95:                 (stack[-1].children if stack else roots).append(node)
96:                 stack.append(node)
97:             elif line.startswith("edit "):
98:                 node = EditBlock(line[5:])
99:                 if not stack:
100:                     raise ValueError("Startup config malformed. edit outside config scope.")
101:                 stack[-1].children.append(node)
102:                 stack.append(node)
103:             elif line == "next":
104:                 if not stack or not isinstance(stack[-1], EditBlock):
105:                     raise ValueError("Startup config malformed. next outside edit scope.")
106:                 stack.pop()
107:             elif line == "end":
108:                 if not stack or not isinstance(stack[-1], ConfigBlock):
109:                     raise ValueError("Startup config malformed. end outside config scope.")
110:                 stack.pop()
111:             else:
112:                 if not stack:
113:                     raise ValueError("Startup config malformed. command outside config scope.")
114:                 stack[-1].children.append(line)
115:     if stack:
116:         raise ValueError("Startup config malformed. unmatched config or edit scope.")
117:     return roots

(End of file - total 117 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d1825c001IpuHR976vr6zM1",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d15ec9001CVKHxoy6epRdK5",
  "callID": "call_6807224ff0cd46b884ea0c4c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/startup_config.py"
    },
    "output": "<path>/source/head/fortinet/common/features/startup_config.py</path>\n<type>file</type>\n<content>\n1: \"\"\"User startup configuration feature.\"\"\"\n2: \n3: import os\n4: \n5: from ..cli_commands import ConfigBlock, EditBlock\n6: from ..env import has_env\n7: from .base import StaticFeature\n8: \n9: \n10: class ApplyStartupConfig(StaticFeature):\n11:     def __init__(self, vm, commander):\n12:         path = \"/config/startup-config.cfg\"\n13:         blocks = parse_startup_config(path) if os.path.exists(path) else []\n14:         blocks = filter_startup_config_blocks(blocks, commander.logger)\n15:         super().__init__(vm, commander, \"startup-config\", blocks)\n16: \n17: \n18: def filter_startup_config_blocks(blocks, logger):\n19:     \"\"\"Skip startup DNS configuration that conflicts with FortiGuard hook DNS.\"\"\"\n20:     if not (\n21:         has_env(\"FOS_FORTIGUARD_HOOKS\")\n22:         and (\n23:             has_env(\"FOS_MGMT_DNS_PRIMARY\", aliases=(\"FTNT_DNS_PRIMARY\",))\n24:             or has_env(\n25:                 \"FOS_MGMT_DNS_SECONDARY\",\n26:                 aliases=(\"FTNT_DNS_SECONDARY\",),\n27:                 legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n28:             )\n29:             or has_env(\"FTNT_DNS_PROTOCOL\")\n30:         )\n31:     ):\n32:         return blocks\n33: \n34:     filtered = [\n35:         block\n36:         for block in blocks\n37:         if not (isinstance(block, ConfigBlock) and block.value == \"system dns\")\n38:     ]\n39:     if len(filtered) != len(blocks):\n40:         logger.warning(\n41:             \"Skipping startup config block 'config system dns' because \"\n42:             \"FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY, \"\n43:             \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n44:         )\n45:     return filtered\n46: \n47: \n48: def _startup_config_commands(config):\n49:     \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n50:     pending = []\n51:     quote = None\n52:     start_line = None\n53:     for number, raw_line in enumerate(config, start=1):\n54:         # Text mode normalizes file line endings. Only remove the delimiter;\n55:         # whitespace and comment/scope-looking lines inside quotes are data.\n56:         line = raw_line.removesuffix(\"\\n\")\n57:         if not pending:\n58:             line = line.lstrip()\n59:             if not line or line.startswith(\"#\"):\n60:                 continue\n61:             start_line = number\n62: \n63:         escaped = False\n64:         for character in line:\n65:             if escaped:\n66:                 escaped = False\n67:             elif character == \"\\\\\":\n68:                 escaped = True\n69:             elif character == quote:\n70:                 quote = None\n71:             elif quote is None and character in {\"'\", '\"'}:\n72:                 quote = character\n73: \n74:         if quote is not None or escaped:\n75:             pending.append(line)\n76:             continue\n77:         pending.append(line.rstrip())\n78:         yield \"\\n\".join(pending)\n79:         pending.clear()\n80: \n81:     if pending:\n82:         reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n83:         raise ValueError(\n84:             f\"Startup config malformed. {reason} starting on line {start_line}.\"\n85:         )\n86: \n87: \n88: def parse_startup_config(path):\n89:     roots = []\n90:     stack = []\n91:     with open(path) as config:\n92:         for line in _startup_config_commands(config):\n93:             if line.startswith(\"config \"):\n94:                 node = ConfigBlock(line[7:])\n95:                 (stack[-1].children if stack else roots).append(node)\n96:                 stack.append(node)\n97:             elif line.startswith(\"edit \"):\n98:                 node = EditBlock(line[5:])\n99:                 if not stack:\n100:                     raise ValueError(\"Startup config malformed. edit outside config scope.\")\n101:                 stack[-1].children.append(node)\n102:                 stack.append(node)\n103:             elif line == \"next\":\n104:                 if not stack or not isinstance(stack[-1], EditBlock):\n105:                     raise ValueError(\"Startup config malformed. next outside edit scope.\")\n106:                 stack.pop()\n107:             elif line == \"end\":\n108:                 if not stack or not isinstance(stack[-1], ConfigBlock):\n109:                     raise ValueError(\"Startup config malformed. end outside config scope.\")\n110:                 stack.pop()\n111:             else:\n112:                 if not stack:\n113:                     raise ValueError(\"Startup config malformed. command outside config scope.\")\n114:                 stack[-1].children.append(line)\n115:     if stack:\n116:         raise ValueError(\"Startup config malformed. unmatched config or edit scope.\")\n117:     return roots\n\n(End of file - total 117 lines)\n</content>",
    "title": "source/head/fortinet/common/features/startup_config.py",
    "metadata": {
      "preview": "\"\"\"User startup configuration feature.\"\"\"\n\nimport os\n\nfrom ..cli_commands import ConfigBlock, EditBlock\nfrom ..env import has_env\nfrom .base import StaticFeature\n\n\nclass ApplyStartupConfig(StaticFeature):\n    def __init__(self, vm, commander):\n        path = \"/config/startup-config.cfg\"\n        blocks = parse_startup_config(path) if os.path.exists(path) else []\n        blocks = filter_startup_config_blocks(blocks, commander.logger)\n        super().__init__(vm, commander, \"startup-config\", blocks)\n\n\ndef filter_startup_config_blocks(blocks, logger):\n    \"\"\"Skip startup DNS configuration that conflicts with FortiGuard hook DNS.\"\"\"\n    if not (",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/startup_config.py",
        "text": "\"\"\"User startup configuration feature.\"\"\"\n\nimport os\n\nfrom ..cli_commands import ConfigBlock, EditBlock\nfrom ..env import has_env\nfrom .base import StaticFeature\n\n\nclass ApplyStartupConfig(StaticFeature):\n    def __init__(self, vm, commander):\n        path = \"/config/startup-config.cfg\"\n        blocks = parse_startup_config(path) if os.path.exists(path) else []\n        blocks = filter_startup_config_blocks(blocks, commander.logger)\n        super().__init__(vm, commander, \"startup-config\", blocks)\n\n\ndef filter_startup_config_blocks(blocks, logger):\n    \"\"\"Skip startup DNS configuration that conflicts with FortiGuard hook DNS.\"\"\"\n    if not (\n        has_env(\"FOS_FORTIGUARD_HOOKS\")\n        and (\n            has_env(\"FOS_MGMT_DNS_PRIMARY\", aliases=(\"FTNT_DNS_PRIMARY\",))\n            or has_env(\n                \"FOS_MGMT_DNS_SECONDARY\",\n                aliases=(\"FTNT_DNS_SECONDARY\",),\n                legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n            )\n            or has_env(\"FTNT_DNS_PROTOCOL\")\n        )\n    ):\n        return blocks\n\n    filtered = [\n        block\n        for block in blocks\n        if not (isinstance(block, ConfigBlock) and block.value == \"system dns\")\n    ]\n    if len(filtered) != len(blocks):\n        logger.warning(\n            \"Skipping startup config block 'config system dns' because \"\n            \"FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY, \"\n            \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n        )\n    return filtered\n\n\ndef _startup_config_commands(config):\n    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n    pending = []\n    quote = None\n    start_line = None\n    for number, raw_line in enumerate(config, start=1):\n        # Text mode normalizes file line endings. Only remove the delimiter;\n        # whitespace and comment/scope-looking lines inside quotes are data.\n        line = raw_line.removesuffix(\"\\n\")\n        if not pending:\n            line = line.lstrip()\n            if not line or line.startswith(\"#\"):\n                continue\n            start_line = number\n\n        escaped = False\n        for character in line:\n            if escaped:\n                escaped = False\n            elif character == \"\\\\\":\n                escaped = True\n            elif character == quote:\n                quote = None\n            elif quote is None and character in {\"'\", '\"'}:\n                quote = character\n\n        if quote is not None or escaped:\n            pending.append(line)\n            continue\n        pending.append(line.rstrip())\n        yield \"\\n\".join(pending)\n        pending.clear()\n\n    if pending:\n        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n        raise ValueError(\n            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n        )\n\n\ndef parse_startup_config(path):\n    roots = []\n    stack = []\n    with open(path) as config:\n        for line in _startup_config_commands(config):\n            if line.startswith(\"config \"):\n                node = ConfigBlock(line[7:])\n                (stack[-1].children if stack else roots).append(node)\n                stack.append(node)\n            elif line.startswith(\"edit \"):\n                node = EditBlock(line[5:])\n                if not stack:\n                    raise ValueError(\"Startup config malformed. edit outside config scope.\")\n                stack[-1].children.append(node)\n                stack.append(node)\n            elif line == \"next\":\n                if not stack or not isinstance(stack[-1], EditBlock):\n                    raise ValueError(\"Startup config malformed. next outside edit scope.\")\n                stack.pop()\n            elif line == \"end\":\n                if not stack or not isinstance(stack[-1], ConfigBlock):\n                    raise ValueError(\"Startup config malformed. end outside config scope.\")\n                stack.pop()\n            else:\n                if not stack:\n                    raise ValueError(\"Startup config malformed. command outside config scope.\")\n                stack[-1].children.append(line)\n    if stack:\n        raise ValueError(\"Startup config malformed. unmatched config or edit scope.\")\n    return roots",
        "lineStart": 1,
        "lineEnd": 117,
        "totalLines": 117,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716224608,
      "end": 1793716224614
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d18268001LTWMC1yyOjHkLl",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d15ec9001CVKHxoy6epRdK5",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 72167,
    "input": 7397,
    "output": 36,
    "reasoning": 670,
    "cache": {
      "read": 64064,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d15ec9001CVKHxoy6epRdK5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716215498,
    "completed": 1793716224620
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 72167,
    "input": 7397,
    "output": 36,
    "reasoning": 670,
    "cache": {
      "read": 64064,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 9
step-start
{
  "type": "step-start",
  "id": "prt_1a1d18b14001a0ltbXkmd7B9TC",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d182710012PgOW4K94onaxs"
}
Reasoning
Startup config parser: `_startup_config_commands` yields logical lines with embedded newlines for quoted strings. Then parse_startup_config treats each yielded logical command. If the line starts with "config "/"edit " after being a multi-line quoted string? Hmm, a quoted string spanning lines is joined with "\n" — the resulting logical command could start with "set ..." typically. But consider the case: the value's first line after lstrip starts with e.g. `set alias "foo` and continuation `bar"`. That becomes a logical command `set alias "foo\nbar"` → children append that string → then flatten_commands sees "\n" in value → _flatten_quoted_lines splits on "\n" and re-joins as continuation lines. Good.

Edge: multi-line quoted strings are yielded with internal `\n` — but what about a multi-line string whose first line starts with "config "? E.g. inside a quoted value? If the first line of the pending command is `config foo "bar` and continuation, then the logical line is `config foo "bar\nbaz"` → parser would see startswith("config ") → ConfigBlock("foo \"bar\nbaz\"")? That would misinterpret. But that's weird CLI anyway. Probably fine.

Another edge: In `_startup_config_commands`, when `pending` is non-empty (continuation), the raw line is appended verbatim (not lstripped) — good per comment. But note: when quote is not None or escaped at line end, `pending.append(line)` without rstrip; when command completes, `pending.append(line.rstrip())`. Fine.

Escaped-quote handling: `escaped` tracks backslash. Consider a line ending with `\` inside a quote... pending continues. OK.

Now the flattening: `_flatten_quoted_lines` used by SetValue and flatten_commands for strings with "\n". One issue: `flatten_commands` for a plain string with "\n" uses defaults `validate_prompt=True, fail_on_error=False` — matches old behavior? Old behavior for a plain multi-line string: previously `flatten_commands` would raise ValueError since CommandSpec forbids "\n" in line. So this is new capability. OK.

But there's a subtlety: SetValue.flatten mutates `lines` in place — fine, local.

Another subtlety in `_flatten_quoted_lines`: `expected_completion_state` for continuation lines: non-last lines expect MULTILINE_PROMPT; last expects CMD_PROMPT. But completion_states for len(lines)==1 is `()`, so it defaults to CMD_PROMPT. OK.

Now — wait, an important issue: in `_flatten_quoted_lines`, `expected` for the last line is CMD_PROMPT but `completion_states` for the last line is `(CMD_PROMPT, MULTILINE_PROMPT)`. With `validate_prompt=False`, expected is None. OK.

Now, one potential correctness issue in cli_commands: `CommandAttempt.on_output` now captures output for `closes_scope` commands ("next"/"end"). The `on_output` calls `output.discard(data)` — discards from terminal buffer. In test_common_scope_errors, data chunks are Data objects with no discard_callback... Actually `Data(chunk)` with discard_callback=None — `discard` sets discarded=True. OK.

Now the "scope commit failure" check: `_validate_completion` checks `attempt.spec.closes_scope` even if capture_output is False — but output is only captured if capture_output or closes_scope. closes_scope includes "next" and "end" lines. But note: `closes_scope` is based on `self.line.strip().lower() in {"next", "end"}`. A command like "next" inside cleanup also counts. Good.

However there's a subtle issue: `CommandSpec("next", continuation=True)`? Not likely.

Another: In `_complete_inflight`, context-loss check happens BEFORE `_validate_completion`. So if a "next" command both fails (Command fail) and changes context, context loss path takes precedence — fine, tests cover.

Now important check: `_complete_inflight` when `state == CMD_PROMPT and self._prompt_context_changed(attempt)` — `_prompt_context_changed` requires before is not None and after is not None. before = prompt context at dispatch; after = at completion. At completion, `_prompt_context` is updated in `on_state` when CMD_PROMPT arrives. Note `on_state` extracts context for CMD_PROMPT before completing inflight. Good.

Potential issue: `_prompt_context` is only updated when context is not None. If a prompt has no context parens, e.g. "fw #", `_extract_prompt_context` returns tuple () — matches? `CLI_PROMPT_CONTEXT_PATTERN` with empty context group matches "fw #". finditer returns match with context = b"" → re.findall on b"" returns [] → returns () (empty tuple). So context = () not None. Good — so "fw #" yields ().

Now `_restore_replay_context` compares `self._prompt_context == target`; `self._prompt_context` may be None if no CMD_PROMPT observed since... Actually on_state sets `_recovering=False` and `_authenticated_once=True` on every CMD_PROMPT, and updates _prompt_context when not None. Hmm: at session loss recovery, the login path. Fine.

Potential bug: `_dispatch_next` early-returns when `self._pending_feature_error is not None` — new. This means during recovery of a pending feature error, no dispatch. `_recover_feature_error` calls `continue_after_error` then `_dispatch_next()`. OK.

Another potential bug: In `_complete_inflight`, on context loss with `RESTART_BLOCK`, `_restart_active_block` sets `self._replay_context_target = self._block_prompt_context`. `_block_prompt_context` is set at submit_block time from `_prompt_context`. But if the block was submitted while _prompt_context was None (e.g. never saw a prompt with context, like initial "fw #" — wait "fw #" yields () not None). _prompt_context becomes None only if no CMD_PROMPT state has been seen yet, or if a CMD_PROMPT output had no matching prompt line... Hmm, _extract_prompt_context returns None if no matches in output. When does on_state get called with CMD_PROMPT and output not containing a prompt? E.g. CMD_PROMPT matched in an earlier chunk and the output for this state is Data(b"") after process_state converts output to empty? In process_state: if output and not matched: on_output(output); output = type(output)(b""). Then _process_state(state, b"") — on_state(CMD_PROMPT, b""). Then _extract_prompt_context(b"") → None → keep old context. Fine, keeps prior.

Now `_block_prompt_context` — the target for replay. If `_block_prompt_context` is None (block submitted before any prompt context was seen — e.g. the very first block dispatched right after login where the Welcome prompt is `fw #` → context ()). So target=() not None. But if `_prompt_context` is None at submit time (e.g., block submitted during activate() before any prompt state? Actually activate is called from _dispatch_next which is called from on_state(CMD_PROMPT) which updated _prompt_context already... unless context was None from that output). If `_replay_context_target` is None, `_restore_replay_context` returns True immediately (no context restoration). That means with None target, replay proceeds without abort — acceptable degradation.

Hmm wait, actually there's a subtle mismatch: `_restart_active_block` sets `self._replay_context_target = self._block_prompt_context`. If `_block_prompt_context` is None (never seen prompt), then `_restore_replay_context` returns True immediately and replays openers. If the scope is partially open (context lost mid-block), we would send "config system interface" while still inside the scope... Actually context loss means we returned to a different prompt (e.g. top-level), so sending openers is fine. But if context changed to a *deeper* scope? Then replaying "config X" inside a nested scope would fail. The `_restore_replay_context` with a target would abort. With None target, no protection. But since context extraction gives () for bare prompts, None is rare. OK.

Now the retry accounting: `_recovery_retries` keyed by block_index. block_index computed as `len(self._active_commands) - len(self._pending) - 1`. When a command completes normally, it's popped already... wait: spec = self._pending.popleft(); block_index = len(active) - len(pending) - 1. If pending originally had 4 commands, popping first leaves 3, index = 4-3-1 = 0. Good.

But when `on_block_complete` is called (pending empty) — no dispatch. OK.

Issue: `_restart_active_block` with `attempt.block_index` — but block_index is None for cleanup commands (passing None into `_recovery_retries.get(None, 0)` — but restart for cleanup is handled separately in session loss; for context loss in cleanup, `_handle_context_loss` reports error. OK).

However, `_restart_active_block(attempt, reason)` when called from `_handle_session_loss` with SessionLossAction.RESTART_BLOCK — attempt.block_index may be None if... dispatched via `_dispatch_command(spec)` without block_index — that's only for the abort command in `_restore_replay_context` (in_context_reset). During context reset, session loss with in_context_reset=True returns early (line 619-623) before reaching action handlers. OK.

Now, `_recovery_retries` keyed by block_index; note `submit_block` resets `_recovery_retries = {}`. Fine.

Potential issue: In `_complete_inflight`, `if self._in_context_reset: self._in_context_reset = False; self._dispatch_next(); return`. This path means the abort command completed. Then `_dispatch_next` → `_restore_replay_context` → context now == target? If abort returned to expected target, proceed. Else `_context_reset_attempted` is True → error. Good, bounded.

But: `_restore_replay_context` checks `self._prompt_context == target`. If target is `()` and current prompt context is `("port1",)` (still in scope after abort?), abort from a config scope returns to parent. Hmm, abort within nested scopes only exits one level. FortiOS `abort` exits the current config scope? Actually in FortiOS, `abort` discards changes in current config scope and exits it. Nested scopes... fine.

Now, session loss during context reset: `_handle_session_loss` resets `_in_context_reset=False` and returns, but `_context_reset_attempted` remains True. After reconnect and prompt, `_dispatch_next` → `_restore_replay_context`: target set, prompt != target (probably), `_context_reset_attempted` True → error "Unable to restore CLI context". Hmm wait — test `test_session_loss_during_context_reset_resumes_after_login` expects reconnect then enter_interface → finish → completed, and abort count 1. Let me trace: prompt(commander, "interface") — that's the context loss trigger? Let me trace the test:

- prompt(commander) → dispatch "config system interface"
- enter_interface: prompt(interface) → dispatch "edit port1"; prompt(port1) → dispatch IP_COMMAND
- prompt(commander, "interface") → IP command completes but context changed from ("port1",) to ("interface",) → context loss → feature returns RESTART_BLOCK (default) → _restart_active_block: retries=0 → retry 1; pending = active_commands; _replay_context_target = _block_prompt_context. What was _block_prompt_context at submit time? submit_block called from activate() — which is called by _activate_next_feature from _dispatch_next from on_state(CMD_PROMPT) — the first prompt(commander) sets _prompt_context = () (from "FGT...#"). So target = ().
- On next on_state CMD_PROMPT: _dispatch_next → _restore_replay_context: target=() but prompt_context=("interface",) ≠ target → _context_reset_attempted False → set True, dispatch "abort" (in_context_reset=True).
- Then in the test: `commander.on_state(SESSION_LOST, ...)` — session lost during the abort (in_context_reset True) → resets _in_context_reset=False, returns. Then `self.reconnect(commander)` → CREDENTIAL_ACCEPTED (sets recovering False, authenticated) then prompt(commander) → CMD_PROMPT with context () → _prompt_context=() ... on_state: not recovering; on_output; then inflight None... then state==CMD_PROMPT and not recovering → _dispatch_next → _restore_replay_context: target=() == _prompt_context=() → clear target, return True → proceed to dispatch "config system interface" (replay). Test expects writes[-1] == "config system interface\r" ✓. Then enter_interface, finish_interface → completed. abort count 1 ✓.

OK so that path works because after session loss, `_handle_session_loss` returned without clearing `_context_reset_attempted`. But wait — after session loss during context reset, `_recovering` is set True by `_handle_session_loss`. Then reconnect: CREDENTIAL_ACCEPTED clears _recovering. Then prompt → dispatch. But hold on: in `_handle_session_loss` for the in_context_reset case, the abort command's attempt was in-flight; `_inflight` cleared. Good.

But here's a subtlety: after session loss during context reset, when the reconnect prompt arrives with context (), it matches target so fine. But what if login returns to context ("interface")? Then `_context_reset_attempted` is still True → error. That's the documented bounded behavior.

Now consider: session loss during context reset but the session-loss handling happens while `_in_context_reset` — the abort's suppress_output ExitStack is closed (line 617-618). Fine.

Now — potential issue in `_handle_session_loss` cleanup retry: `self._cleanup_retries[id(attempt.spec)]` — keyed by id(spec). `CommandSpec` is frozen dataclass; id-based keying is per-instance. Cleanup deque holds the same spec objects so id stable. But two different specs could collide if one is garbage collected and another allocated at same address. In practice cleanup commands are held in `self._cleanup` deque while retrying, and `_cleanup_retries.pop` on completion. But consider: cleanup retries counter persists in `_cleanup_retries` after the command completes? In `_complete_inflight`, `self._cleanup_retries.pop(id(attempt.spec), None)` on success. On error (handle_work_error → continue_after_error), `_cleanup_retries.clear()` in continue_after_error. OK. But id-collision: after pop, if the spec object is discarded and a later spec allocated at same id... The retries would incorrectly carry over. Edge-casey; cleanup commands come from `_schedule_feature_cleanup` flatten each time — new objects each call. `_cleanup_retries` entries are removed on completion or cleared on error. Remaining risk: session-loss retry increments counter, then command completes → popped. Fine. Minor.

Now `_validate_completion` raising RuntimeError caught in `_complete_inflight` only when `state == CMD_PROMPT`; else re-raised. When re-raised from `_complete_inflight`, `_inflight` already None and suppression closed. The driver's process_state propagates. Fine per test test_unusable_completion_prompt.

Hmm — but wait: with `continue_on_error=True` and a completion at CONFIRMATION state failing validation, the RuntimeError propagates out of process_state — test asserts that ("An interactive prompt cannot safely advance"). OK intentional.

Now the credentials feature: `on_command_dispatched` for "exit" calls `_activate_desired_credentials()` — activates desired creds BEFORE the exit is sent. The driver's `_credentials` is vm.desired_credentials? In the test, vm.desired_credentials = Credentials(username, password) and driver constructed with `credentials` = ? Let me check: driver created with `credentials` param — in test `FOSCliDriver(terminal, commander, credentials, logger, ...)`. Which credentials object? `credentials = Credentials("admin", "oldpass")` — the driver holds the "current" credentials. `vm.desired_credentials` is separate. `activate_desired` sets driver.remember_current_credentials() then credentials.username = username; credentials.password = password — mutating the driver's credentials object. OK.

Now the exit command spec: `expected_completion_state=FOSCliState.PROVIDE_USERNAME`, `session_loss=CONTINUE`, `capture_output=True`, `fail_on_error=True`. Context loss default: session_loss != RESTART_BLOCK → context_loss = FAIL. If logout returns directly to CLI prompt (no login prompt), context_loss triggers? Wait — completing at a CLI prompt when expected PROVIDE_USERNAME: `_complete_inflight` first checks `state == CMD_PROMPT and _prompt_context_changed(attempt)`. If exit returns to a CLI prompt with same context... context before exit was probably top-level () or ("Interim",)? Actually exit from config mode returns to a different context → `_prompt_context_changed` true (exit is in `_command_may_change_context` whitelist — so NOT considered context loss). Then `_validate_completion` raises "expected PROVIDE_USERNAME, received CMD_PROMPT" → `_handle_work_error` → recover. That matches test_logout_must_return_to_login (expects RuntimeError "expected PROVIDE_USERNAME" with default continue_on_error=False → _handle_work_error raises). Good.

Now `on_command_dispatched` for "exit" activates desired credentials — hmm, but the block dispatch for "exit" happens via `_dispatch_command` which calls on_command_dispatched before writing. So the desired password is set before exit is sent. Then the login prompt appears, driver answers with desired credentials. Good.

But wait — there's a potential issue with `_activate_desired_credentials` being idempotent via `_desired_credentials_activated`. It's also called from on_complete (after the last block completes). Since on_command_dispatched already activated at exit dispatch, on_complete's call is a no-op. Fine.

Edge: What if the "exit" command never dispatches because session loss happens during "end"? auto_logout="end" case: end_response returns LOGIN. Then commander handles... state PROVIDE_USERNAME with _authenticated_once → _handle_session_loss. attempt for "end" in flight. on_session_loss("end") → not password command; `self._activate_after_admin_commit` is True and line == "next"? No, line is "end" — falls to `if self._password_change_committed` — is it committed? on_command_executed for the password "set password" sets _activate_after_admin_commit=True. Then "next" completes: on_command_executed sees line "next" with _activate_after_admin_commit → activates desired, sets committed=True. Then "end" completes → on_command_executed: line "end" not password, not "next" → nothing. Hmm wait the block is `ConfigBlock("system admin", [EditBlock(...)])` → commands: config system admin, edit user, set password, next, end. Then end_response returns LOGIN (auto_logout == "end" and end_count==2)? end_count: first "end" is for password-policy ConfigBlock ("end" #1), second for admin block. So second end returns LOGIN.

Sequence: password-policy config: set status disable, end#1 → fw #. Then config system admin → edit admin → set password newpass → (current password prompt → driver responds) → next → ADMIN_PROMPT (normal) → end#2 → LOGIN. On end#2 completion: state would be... The response "Login incorrect\r\nfw login:" — the driver sees PROVIDE_USERNAME state; commander's on_state(PROVIDE_USERNAME) with _authenticated_once → _handle_session_loss. attempt = "end" in flight. on_session_loss("end"): not exit, not password command, `self._activate_after_admin_commit and attempt.spec.line == "next"` — line is "end" not "next" → falls through to `if self._password_change_committed:` → True (set by on_command_executed for "next") → CONTINUE → pending cleared. Then after login, `end`... wait no — pending was cleared, so "exit" from the admin-relogin CommandSequence is also cleared! Then the block is done; on_block_complete... hmm, after pending cleared, next prompt dispatches... `_dispatch_next` with empty pending → `_call_feature(self._active_feature.on_block_complete)` → StaticFeature._submit_next → no blocks left → on_complete → feature_complete. So test expects `conn.writes.count(b"exit\r"), 1`? For auto_logout="end": does "exit" ever get sent? Test test_fortios_logout_at_commit_does_not_replay_password_change: subtests for next and end; asserts set password once, exit once, newpass twice. For auto_logout="end": after end#2 → login (newpass first use #1) → ... then the feature completes (pending cleared) → next feature "probe"... but wait, if pending cleared, exit never sent, then how does exit count == 1? Hmm. Unless the flow: end#2 completes at CMD_PROMPT? Let me reconsider: end_response returns LOGIN = b"Login incorrect\r\nfw login:\r\n" if auto_logout=="end" and end_count==2. Hmm wait, for the first end (password-policy), end_count=1 → returns b"fw #\r\n". Second end → LOGIN.

Hmm wait — but actually maybe on_state(PROVIDE_USERNAME) → _handle_session_loss → on_session_loss("end") → _password_change_committed is True → CONTINUE → pending.clear() — clears "exit". Then driver responds to login with desired creds → CREDENTIAL_ACCEPTED / prompt → feature completes without sending exit. Then conn.writes.count(b"exit\r") would be 0, not 1. But test asserts 1. So my trace must be wrong.

Let me re-check: is `end` here `closes_scope` — yes. `_complete_inflight` for "end" at CMD_PROMPT... but the state when end#2's response arrives: "Login incorrect\r\nfw login:\r\n" — the driver's expect matches PROVIDE_USERNAME pattern first (login:). So commander.on_state(PROVIDE_USERNAME, ...) → _handle_session_loss.

Hmm, but wait: `_password_change_committed` — set by on_command_executed for "next". But on_command_executed is called in _complete_inflight only when the command completes normally at its completion state. "next" completes at ADMIN_PROMPT (CMD_PROMPT) → on_command_executed sets _activate_after_admin_commit=True... wait no. Let me recheck on_command_executed:

```python
def on_command_executed(self, command, state):
    line = command.spec.line
    if self._is_password_command(line):
        self._activate_after_admin_commit = True
    elif self._activate_after_admin_commit and line == "next":
        self._activate_desired_credentials()
        self._activate_after_admin_commit = False
        self._password_change_committed = True
```

Wait, "set password newpass" is dispatched → but there's a CURRENT_PASSWORD prompt: FortiOS asks "Please enter current administrator password:". The driver handles CURRENT_PASSWORD state (responds with current creds). But does the password command complete? The command's completion state is default CMD_PROMPT; after responding to CURRENT_PASSWORD, ADMIN_PROMPT appears → completes. on_command_executed("set password newpass") → _activate_after_admin_commit = True.

Then "next" dispatched → completes at ADMIN_PROMPT (next returns to edit? no—next closes edit → returns to config system admin context, still ADMIN_PROMPT context "admin"). on_command_executed("next") → activates desired creds, _activate_after_admin_commit=False, _password_change_committed=True.

Then "end" dispatched (closes_scope) → completes at... end_response #2 → LOGIN. Driver sees PROVIDE_USERNAME. Commander on_state(PROVIDE_USERNAME, authenticated_once=True) → _handle_session_loss → on_session_loss("end") → _password_change_committed → CONTINUE → pending.clear() → "exit" dropped.

Then login with newpass (#1) → prompt → _dispatch_next: pending empty → on_block_complete → _submit_next → no blocks → on_complete → feature_complete → next feature "probe". So exit count = 0. But test asserts 1 and newpass count 2.

Hmm, so maybe I'm wrong: maybe `_handle_session_loss` is not triggered by PROVIDE_USERNAME here because... `if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:` → _handle_session_loss(). That is in on_state. But wait — order in on_state: first `if state == FOSCliState.CMD_PROMPT:` block (no). Then `if self._pending_feature_error is not None:` no. Then on_output. Then `if state == SESSION_LOST:` no. `if state == PROVIDE_USERNAME and self._authenticated_once:` yes → _handle_session_loss. Yes triggered.

So exit would be dropped... unless the flow is different: maybe for auto_logout="end", end_count==2 corresponds to... wait there are only two `end` commands in the feature: password-policy block end and admin block end. So end_count==2 on the admin end. Hmm.

Wait — maybe the "end" of the admin block doesn't trigger PROVIDE_USERNAME handling to clear pending, because `_handle_session_loss` calls on_session_loss which returns CONTINUE only via the `_password_change_committed` branch — which clears pending including exit. Test asserts exit count == 1... Contradiction? Let me re-read the test more carefully.

Actually wait, maybe for auto_logout="end", the flow is: end#2 → LOGIN. But before that, did "next" get dispatched at all? In auto_logout="end" mode, "next" response is ADMIN_PROMPT (the dict: `b"next\r": LOGIN if auto_logout == "next" else ADMIN_PROMPT`). Yes next → ADMIN_PROMPT.

Hmm, but hold on — after "next" completes, `_complete_inflight` → context check: prompt_context_before for "next" was ("admin",)? and after also ("admin",) → unchanged → validate → on_command_executed → next... then dispatch "end".

Then end → LOGIN → _handle_session_loss clears pending (exit dropped) → driver login flow: PROVIDE_USERNAME → driver responds with credentials.username... The driver's credentials object was mutated by activate_desired (during on_command_executed of "next"). So login "admin"/newpass (#1). Welcome → prompt → feature completes → following feature "probe". exit count = 0.

But test asserts `self.assertEqual(conn.writes.count(b"exit\r"), 1)` for both subtests. So something's off in my trace. Maybe `_handle_session_loss` is NOT invoked because at the time of PROVIDE_USERNAME, `_inflight` is... in flight "end" yes. Hmm.

Wait — maybe the PROVIDE_USERNAME state doesn't reach commander.on_state with _authenticated_once True because... Actually, hmm, wait: maybe end#2's response LOGIN arrives and the driver processes PROVIDE_USERNAME → responds with username. The commander's on_state(PROVIDE_USERNAME) → _handle_session_loss → attempt "end" → on_session_loss returns CONTINUE (via _password_change_committed) → pending.clear(). Yes exit dropped.

Unless... the `_password_change_committed` branch. Hmm wait, order of checks in on_session_loss:

```python
if attempt.spec.line == "exit": return CONTINUE
if self._is_password_command(...): ...
if self._activate_after_admin_commit and attempt.spec.line == "next": ...
if self._password_change_committed: return CONTINUE
return super().on_session_loss(attempt)
```

For "end": _password_change_committed True → CONTINUE → pending.clear() → exit dropped.

So test would fail unless... hmm, unless on_state for PROVIDE_USERNAME is not called by the driver before the login completes? Let me check the driver's process flow: `_process_state(PROVIDE_USERNAME, output)` — calls _handle_state(state) at... for CMD_PROMPT first, else `self._commander.on_state(state, output)` then `if state != CMD_PROMPT: self._handle_state(state)`. So commander.on_state(PROVIDE_USERNAME) IS called.

Hmm, wait — maybe the response for end#2 is `LOGIN` but with `b"Login incorrect\r\n"` prefix: LOGIN = b"fw login:\r\n". end_response returns LOGIN — plain "fw login:\r\n". OK.

So pending cleared, exit never sent, exit count 0 ≠ 1. Unless... the pending at that time doesn't contain exit? The admin block is `ConfigBlock("system admin", [EditBlock(...)])` → commands: "config system admin", "edit admin", [set password, next], "end". Then admin-relogin CommandSequence is a separate block submitted by StaticFeature._submit_next after on_block_complete. So "exit" is in a *separate* block, not pending with "end". `_handle_session_loss` CONTINUE → `self._pending.clear()` — clears the current block's remaining commands (nothing left, since end was last). The "exit" block hasn't been submitted yet! So after login, on_block_complete → _submit_next submits admin-relogin block → exit dispatched → logout → login (newpass #2) → feature completes.

Now exit count == 1 ✓ and newpass count == 2 ✓ (login once after end-logout, once after exit-logout).

But wait: after the session-loss CONTINUE, pending is empty → the commander would dispatch on_block_complete at next prompt → _submit_next → admin-relogin block with "exit". But the "exit" dispatch expects PROVIDE_USERNAME. At the prompt after first login, "exit" is sent → response LOGIN → PROVIDE_USERNAME → on_command_dispatched("exit") already activated creds (idempotent) → expected_completion_state=PROVIDE_USERNAME → completes ✓. Then driver answers login with newpass (#2) → Welcome/prompt → feature complete → probe. Test asserts writes[logout+1:] == [username, password, probe] ✓.

OK, so the flow works. Good — I mis-traced initially; the exit is in a separate block.

Now, `on_command_dispatched` calling `_activate_desired_credentials` at "exit" dispatch — the credentials are switched before exit. But what if exit is dispatched while still... fine.

Edge: `on_session_loss` for "exit" returns CONTINUE — pending cleared, exit not replayed. Then after login, on_block_complete → _submit_next... but wait, the admin-relogin block had only "exit"; pending cleared; on next prompt, on_block_complete → feature completes. Good.

Now, one more concern: `CommandSpec("exit", ... expected_completion_state=PROVIDE_USERNAME)` and `fail_on_error=True`. `closes_scope` is False ("exit" not in {"next","end"}). OK.

But here's a question: when "exit" completes at PROVIDE_USERNAME, `_complete_inflight(PROVIDE_USERNAME)`: `_prompt_context_changed`? state != CMD_PROMPT so no. `_validate_completion`: fail_on_error → COMMAND_FAILURE_PATTERN.search(attempt.output) — output captured (capture_output=True). "exit" output = "fw login:" no failure. expected==state ✓. Then not in cleanup; not standard output; on_command_executed(attempt, PROVIDE_USERNAME) — line "exit": not password, not "next" → nothing. Then not busy, feature is active → on_block_complete → _submit_next → no blocks → on_complete (activate desired - already done) → feature_complete → activate next feature. OK.

Now — a real potential issue: `CredentialsFeature.on_command_dispatched` checks `attempt.spec.line == "exit"`, but a *cleanup* or context-reset "abort"... not exit. Also `on_session_loss` for "exit" — but the spec sets session_loss=CONTINUE anyway, so base returns CONTINUE. The explicit branch is redundant but harmless.

Now let me look at pki.py diff context: it only changed a comment. And launch.py: KernelPanicError handling. Let me read launch.py relevant section and check `_bootstrap_error`, `stop`, etc. Also check `process_state` exception handling: KernelPanicError → self.stop(); raise. Good.

Now potential issue: KernelPanicError raised from `_handle_state` in driver (`_kernel_panic` handler) — `_handle_state` logs exception and re-raises. Then process_state → launch catches KernelPanicError → stop, raise. But note: `commander.on_state(FOSCliState.KERNEL_PANIC, Data(panic))` is called BEFORE `_handle_state` (since state != CMD_PROMPT, on_state first then _handle_state). Commander.on_state(KERNEL_PANIC) — state not handled in commander: falls through... `if self._inflight and state in completion_states` — completion_states default (CMD_PROMPT,) — KERNEL_PANIC not in → skip. Then `if state == CMD_PROMPT and not self._recovering:` no. So harmless. Test asserts commander.on_state called once with KERNEL_PANIC. OK.

Wait — but on_state with output: `self.on_output(output)` — if inflight exists, on_output may capture. Fine.

Kernel panic pattern requires "CPU: N PID: N Comm: ..." line following. Reasonable.

Now the terminal change: `expect` on timeout returns `Data(self._buffer, self._discard_prefix, received_new_data=...)` — the Data wraps the LIVE bytearray? `Data.__init__` does `self.value = bytes(value)` — copies. OK.

Important: the timeout Data now contains the ENTIRE unmatched buffer, including data from previous expect calls that was left buffered. Previously it returned only newly received bytes since this call. Consumers that discard the timeout data will now discard the entire buffer (prefix check passes since data == full buffer). Consumers that inspect without discarding keep it. This changes `CommandAttempt.on_output` behavior on timeout: previously the attempt captured only new bytes per call; now the first timeout inspection captures the entire buffer (including pre-command retained bytes), and subsequent timeout inspections would re-capture the same buffer again (duplicating it in attempt.output!) — wait, does on_output discard? Yes: `on_output` extends output and calls `output.discard(data)` — so the buffer is consumed. So duplicate capture avoided because discard clears buffer. But a feature's `on_output` (non-capturing, e.g. image_info feature reading `get system status` output) — how do they handle timeout Data? If a feature inspects output on timeout without discarding, next call returns same buffer again → duplicate processing. The README documents: "Inspecting timeout Data leaves those bytes buffered so later input can complete a partial token. Calling discard() explicitly consumes the view."

Check features like capture_config/license that use on_output with timeout data. The test test_timeout_capture_consumes_retained_prefix_and_new_bytes shows CommandAttempt.on_output consumes everything. But features' on_output implementations — e.g. `ImageInfoFeature` — do they discard? Let me grep features for `discard`.

Also there's a subtle duplication risk: In `on_output` (commander), `if not isinstance(output, Data)` etc. The driver calls `self._commander.on_output(output)` for unmatched output, then sets `output = type(output)(b"")` — creates new empty Data WITHOUT discard callback. Then `_process_state(state, b"")`. Hmm wait — but then the original output Data (buffer view) is handed to commander.on_output → features on_output. If a feature inspects but doesn't discard, buffer retains. Then next state cycle: _next_state returns TN_TIMEOUT or UNKNOWN with the same buffer again → commander.on_output again → feature sees same bytes again → potential duplicate handling. Before this change, the timeout Data contained only newly received bytes and was NOT discarded automatically either ("Timeout bytes are not consumed automatically" per README). But previously each timeout Data contained only the new bytes, so repeated inspection gave different content; now repeated inspection gives cumulative buffer. Features that match on the timeout data (e.g., waiting for a pattern in on_output) would match the same content repeatedly? They'd typically discard matched data. Let me check the features' on_output implementations to see whether they handle timeout data correctly — capture_config.py, license.py, image_info.py, etc.

Also: `_enforce_buffer_limit` raising RuntimeError — with timeout Data wrapping whole buffer, buffer can only be cleared via discard. OK.

Also `_discard_prefix`: Data from timeout has value == entire buffer; discard_callback=_discard_prefix; buffer.startswith(data) True → cleared. Fine.

Another subtlety: in `expect`, when a match is found, `consumed = bytes(self._buffer[:match.end()])`, `del self._buffer[:match.end()]`, returns `Data(consumed)` — no discard callback. Fine (already consumed).

But now with `received_new_data`: in `_next_state`, `state = UNKNOWN if output.received_new_data else TN_TIMEOUT`. `received_new_data` is True if any new bytes arrived during this expect call. But note: `received_new_data` starts False; `result = self._match(regex_list)` first — if no match and no new data and deadline expires immediately → TN_TIMEOUT. Good.

But wait: there's a bug-ish subtlety — `Data(b"")` default `received_new_data = bool(self.value)` = False. In process_state, `output = type(output)(b"")` → received_new_data False. Then `_process_state(state, b"")` → on_state(state, empty) — for UNKNOWN: `_unknown()` handler. Fine.

Now, the stall timer: `if output and not matched: on_output; if state == UNKNOWN: _note_unknown_output()`. With the new logic, UNKNOWN only when fresh input. _note_unknown_output resets timer on each fresh-input unknown. Then `_recover_unknown_stall` only called in `_timeout` handler (TN_TIMEOUT). Hmm: previously, with retained bytes, each timeout with output → UNKNOWN → _note_unknown_output → timer reset repeatedly → stall never progressed? Previously: `state = TN_TIMEOUT if not output else UNKNOWN`. With retained output across spins, each spin returned UNKNOWN (if bytes were read during that expect) or TN_TIMEOUT (if no bytes this expect). The UNKNOWN handler does nothing except idle_spins for REBOOTING. `_note_unknown_output` resets `_unknown_started_at` each time UNKNOWN occurred. `_recover_unknown_stall` runs only on TN_TIMEOUT. So before: with a stuck stream continuously producing unknown bytes, each expect gets fresh data → UNKNOWN → timer reset → never recovers. After: same — UNKNOWN on fresh data resets timer. Hmm, the change makes TN_TIMEOUT occur when buffer unchanged (idle), which is the case that lets the stall recovery progress. Before, if bytes were still trickling, UNKNOWN; when stream stops, TN_TIMEOUT → recovery proceeds. Wait but before, when stream stops, output on timeout was only the bytes received during that expect call = none → TN_TIMEOUT → recovery. Same. The real behavioral change: before, when the buffer had retained bytes and no new data during the expect, output was empty → TN_TIMEOUT. After, output is the retained buffer but received_new_data False → TN_TIMEOUT. Consistent. The change is mainly: timeout Data now exposes the full retained buffer (so features/patterns can complete partial tokens) rather than only new bytes.

Potential regression: previously, TN_TIMEOUT output was `Data(bytes(received), ...)` — the bytes received during the expect call, with discard callback that would try to discard from the buffer. If a consumer discarded those bytes, the buffer would lose them. Now the timeout Data includes the full buffer; a consumer that discards consumes everything. Is there a consumer that previously relied on discarding timeout output of just the new bytes while keeping older buffer content? E.g. commander._inspect_output discards when recovering (clears everything — fine). Features on_output that discard partial matched content — e.g. license feature matching "VM license install failed" in output then discarding? Let me check the features using on_output with discard semantics.

Let me grep the fortinet features for `discard` and `on_output`.

Also check `CommandAttempt.on_output` — for capture_output commands, every on_output call extends and discards everything. So during a capture command, unmatched (timeout) output is fully captured and consumed. That means the commander/driver's pattern matching... wait, but the driver's expect consumes matched patterns; unmatched output is passed to commander.on_output → inflight.on_output → captures and discards entire buffer. This means for a capture_output command, ANY unrecognized output is consumed into attempt.output. That was already the behavior (capture_output=True previously). But now `closes_scope` commands (next/end) also capture — new behavior, intended per docs.

Hmm, but wait: there's an interplay issue. For a closes_scope command like "next", output arriving before the completion prompt (e.g. "Command fail. Return code -61.") gets captured into attempt.output. But that output ALSO goes through driver state matching... Actually the driver processes serially: each expect call returns either a matched state or timeout data. Unmatched output → on_output → attempt captures (and discards). Matched CMD_PROMPT → on_state → _complete_inflight → validate checks attempt.output for failure pattern. The failure text may span multiple reads (test shows chunked). Since each unmatched chunk is captured, by the time CMD_PROMPT matches, the full failure text is in attempt.output.

But here's a subtlety: the failure pattern match happens in the attempt output which is consumed — but the driver's state patterns also run against the buffer. Before attempt capture, is the failure line consumed from the buffer? The expect call that returned the failure text chunk as timeout data: the commander captures and discards it. Good.

Now — the concern in `_validate_completion`: for closes_scope commands, output is captured regardless of capture_output. But `_handle_context_loss` for closes_scope commands with context change: e.g. "next" fails with "Command fail" AND prompt context changes? In test_failed_next_ejects_before_end, next fails with return code -5 and prompt stays (port1). Fine.

Consider "next" succeeding but returning to parent scope: context before ("port1",), after ("interface",). `_prompt_context_changed` → `_command_may_change_context("next")` → True → not a context loss. Good.

Now potential ordering issue in `_complete_inflight`: context-loss check occurs BEFORE `_validate_completion`, so a scope-closing command that fails (Command fail) and whose context changes → context loss path instead of the mandatory failure error. Docs say scope commit failure is "always fatal" — but if context changes, feature's on_context_loss may restart the block, losing the failure error? Hmm, but a failed `next` typically stays in the same scope. Edge case; maybe fine.

Now — a significant one: `_restart_active_block` sets `_replay_context_target = self._block_prompt_context`, and `_restore_replay_context` compares with `self._prompt_context`. But `_block_prompt_context` was captured at submit time — the context at which the block's first command will run. During replay after context loss, current prompt context might differ (e.g. after a session loss + reconnect, the prompt context could be anything). The abort mechanism handles it.

But note: `_restore_replay_context` sends `CommandSpec("abort", suppress_output=True)` with default session_loss=RESTART_BLOCK and context_loss=RESTART_BLOCK. If abort itself triggers a context change... `_complete_inflight` for abort with `_in_context_reset=True` returns early after dispatch_next — skips context-loss handling for abort. Good.

Now `id(spec)` for `_cleanup_retries` — as noted, minor.

Now — `_dispatch_next` gating on `self._pending_feature_error is not None`: This prevents dispatch while an error is pending. But `_complete_inflight` after `_handle_context_loss` calls `_dispatch_next()` when no pending error. OK.

Another potential issue: In `_complete_inflight`, when `state == CMD_PROMPT` and validation raises → `_handle_work_error(error)` → if not continue_on_error, raises out of `_complete_inflight` → propagates through on_state → process_state. But `_inflight` was already set to None and suppression closed. Feature remains active with pending commands. Fine.

Now the `_recover_feature_error` path: `continue_after_error(error, at_command_prompt=True)` — requires `self._active_feature is not None or self._in_cleanup`. If error occurred at CMD_PROMPT with active feature, it schedules cleanup and clears. Then `_dispatch_next` proceeds to next feature. OK.

Now check `on_state` change: moved `CMD_PROMPT` authenticated/recovering reset to the top. Previously, `if state == FOSCliState.CMD_PROMPT: self._authenticated_once = True` occurred later (after session-loss handling). Now at top with `self._recovering = False`. This means: during session recovery (recovering=True), a CMD_PROMPT state (e.g. after login, prompt appears without Welcome) now sets _recovering=False BEFORE the pending-error block. Previously the prompt didn't clear _recovering. This changes recovery flow: after session loss, when the login prompt appears... PROVIDE_USERNAME → driver responds → CMD_PROMPT arrives → now _recovering=False immediately → dispatch proceeds at prompt. Test test_login_without_welcome_resumes_replay covers this.

But wait — danger: during session loss recovery, a stale CMD_PROMPT could clear _recovering prematurely and dispatch commands while the driver is mid-login? The driver's login flow: PROVIDE_USERNAME → responds username → PROVIDE_PASSWORD → password → CREDENTIAL_ACCEPTED or prompt. If credentials accepted → prompt. A CMD_PROMPT implies we're at a CLI prompt, so dispatch is safe. But there's a scenario: SESSION_LOST banner appears while still logged in? The SESSION_LOST pattern is the license-registration admin-session removal. After that, FortiOS returns to login prompt. A CMD_PROMPT from before... buffers are sequential, so CMD_PROMPT after session loss means we got back to a prompt — could be a pre-login prompt? Prompts require auth. OK.

Hmm, but consider: `_handle_session_loss` sets _recovering=True and schedules replay. The next states: PROVIDE_USERNAME → driver responds → PROVIDE_PASSWORD → responds → CREDENTIAL_ACCEPTED or CMD_PROMPT. With the new top-of-on_state code, CMD_PROMPT sets _recovering=False and (pending error None) proceeds: on_output, then inflight None, then CMD_PROMPT → _dispatch_next → _restore_replay_context → replay. That's the test's expectation. But what if the driver is set to respond with recovery credentials and a "Login incorrect" follows? The sequence: PROVIDE_USERNAME responded → PROVIDE_PASSWORD responded → CREDENTIAL_REJECTED state (not CMD_PROMPT) → _recovering stays... but on_state(CREDENTIAL_REJECTED) doesn't reset _recovering. OK.

One more: on_state top block sets `self._authenticated_once = True; self._recovering = False` for CMD_PROMPT even when `_pending_feature_error is not None`. Then the pending-error block: `if state == CMD_PROMPT: self._recover_feature_error()`. Fine.

Now, `test_common_stack_boundaries` change: `initial_prompt` — because timeout Data now exposes the full buffer, tests adjusted. Note `test_idle_read_exposes_retained_prompt_newline`: the login response "Welcome!\r\nfw #\r\n" — expect matched CMD_PROMPT at "fw #" (without trailing newline?). The pattern `[#$][ \t]*\r?$` — match ends at "#" (the \r?\n is optional). So "\n" remains buffered. Next expect times out with buffer "\n" → attempt.output == b"\n". Previously the attempt output was only newly received bytes = b"" on the idle spin. Hmm — this means for capture commands, attempt.output now includes trailing junk ("\n" after prompt) retained from earlier reads. That affects... COMMAND_FAILURE_PATTERN search over attempt.output — "\n" harmless. But it also affects features matching output content (e.g. capture_config musters output). Retained bytes are legit console output that previously got discarded... wait, previously were they discarded? Previously timeout Data contained newly-received bytes with discard callback; the test previously asserted attempt.output == b"" on idle. The trailing "\n" was received during the login expect (after the prompt match) and stayed buffered. In the old code, on the next spin, expect found no match and no new data → returned Data(b"") — the "\n" stayed in buffer forever, never captured. Now it's exposed on first timeout and captured by attempt.on_output → discarded from buffer. So behavior change: leftover bytes after a match now get consumed by capturing commands. This could affect features that parse captured output — extra trailing "\n" harmless generally.

But here's a real concern: `on_prompt_echo` — `if self.on_output(output).discarded: return`. Fine.

And `_inspect_output`: `if self._recovering: output.discard()` — during recovery, unmatched output discarded. OK.

Now — big question: does anything consume the timeout Data without discarding, causing duplicate processing? `CommandAttempt.on_output` always discards when it captures. Features with on_output implementations: check capture_config.py and others. They're unchanged by this PR but their behavior materially interacts. If a feature's on_output inspects data without discarding (e.g., looking for a marker), the same buffer will be re-inspected on subsequent timeouts → the feature may react multiple times to the same content. Previously, each timeout delivered only new bytes, so repeated inspection gave different content; now repeated inspection gives cumulative buffer. If a feature reacts to a pattern found in the buffer and doesn't discard, it would now react repeatedly (each spin) where before it reacted once (only when new bytes arrived... well, actually before, if the pattern was split across reads, it never matched until enough new bytes arrived; after matching, it would discard? need to check).

Let me grep features for `def on_output` and `discard`.

Also the `_next_state` UNKNOWN vs TN_TIMEOUT: with retained bytes, first timeout after a match returns UNKNOWN (fresh data) — note: `received_new_data=True` even though the data may have been received during a previous expect call that matched! Wait: expect matched → returns; next call: result=_match immediately — if no match, loop: `remaining <= 0`? deadline = now+1s, so remaining>0; get(remaining) waits. If data arrives → received_new_data=True → UNKNOWN. If no data → after timeout, TN_TIMEOUT with received_new_data=False. Good: TN_TIMEOUT when idle.

But subtle: first call after a match, if the buffer already contains a partial token and NO new data arrives within the 1s timeout → TN_TIMEOUT (idle) — correct per comment ("unchanged buffer is still idle").

Now the driver stall logic: TN_TIMEOUT → `_timeout` handler → `_recover_unknown_stall` — sends newline if stuck > 30s. `_note_unknown_output` on UNKNOWN resets timer. OK.

Now let's check `test_common_terminal_driver.py` change: `terminal_buffer_limit_bytes` test now expects FTNT_ to win over FOS_. env.get_env("FOS_TERMINAL_BUFFER_LIMIT_BYTES") → _candidate_names yields FTNT_TERMINAL_BUFFER_LIMIT_BYTES first, then FOS_. So FTNT wins. But env.py is NOT in the changed list — it's pre-existing? The manifest lists env.py as a head file (both revisions presumably). Since the diff doesn't include env.py, it's unchanged. But wait — terminal.py's `BUFFER_LIMIT_ENV = "FOS_TERMINAL_BUFFER_LIMIT_BYTES"` and error message uses BUFFER_LIMIT_ENV — fine.

Hmm, but the terminal.py diff changed `self._logger.log(TRACE_LEVEL - 1, ...)` → `TRACE_LEVEL`. And RAW_SERIAL_LOG_ENV is "FOS_LOG_RAW_SERIAL" → get_env yields FTNT_LOG_RAW_SERIAL first. Test covers both. OK.

Now let me look at the remaining tests and files: test_common_stack_parsing.py head (RecordingFeature, SerialConnection, make_stack), test_common_stack_boundaries head, launch.py, pki.py changed comment, and the READMEs. Also check that `flatten_commands` string-with-newline path is exercised by startup config: parse_startup_config appends raw logical lines (possibly containing \n) as children strings → flatten_commands handles. But note: a logical line from a quoted value could start with "config " (e.g. `config system foo "abc` ... no—) hmm: if a quoted multi-line value's first line starts with "config "? In FortiOS config files, quoted values follow `set X "` so the first line starts with "set ". Could a multi-line quoted string belong to something else? Rare. Not a finding.

But here's a real parsing concern: `_startup_config_commands` treats a line that *opens* a quote and doesn't close it as a continuation — correct. But what about a line with a quote inside a comment? Comments are skipped only when not in pending (line.startswith("#")). A quoted string containing "#" lines is data — handled since pending non-empty. Good.

Edge: `escaped` at end-of-line continues the pending even if quote is None (backslash continuation outside quotes). Then reason "unfinished line continuation". OK.

Edge: What if `pending` is non-empty and the line is empty (blank line inside quote)? pending.append("") — verbatim. Good.

Edge: The `rstrip` on the final line of a completed command: pending lines include the first line possibly with leading whitespace removed (lstrip) but internal lines verbatim. Then `_flatten_quoted_lines` sends each line — wait! The logical command yielded is "\n".join(pending), then parse_startup_config appends it as a plain string child; at flatten time, `flatten_commands` splits on "\n" and each line becomes a CommandSpec — but CommandSpec lines are sent as-is with \r appended. The continuation lines preserve internal whitespace verbatim (not lstripped) — matches "whitespace ... inside quotes are data". But the FIRST line was lstripped during parsing — leading whitespace of the command stripped. Fine.

Hmm wait, one issue: in `_startup_config_commands`, when `pending` is empty and the line starts a new command, the line is `lstrip()`ed but NOT rstripped at that point; rstrip happens only when the command completes (pending.append(line.rstrip())). And continuation lines are appended verbatim (no rstrip) even for the closing line? Let's see: when the quote closes on a continuation line, `pending.append(line.rstrip())` — rstrip applied. But interior continuation lines (still open quote) appended without rstrip — preserved verbatim including trailing spaces. Good.

Now — `_flatten_quoted_lines` for these: `expected_completion_state` defaults validate_prompt=True → last line must complete at CMD_PROMPT, others at MULTILINE_PROMPT. For a quoted set command spanning lines, continuation prompt is ">" (MULTILINE_PROMPT). Good.

But what about `flatten_commands` multi-line strings used directly (not via SetValue)? Defaults: fail_on_error=False, validate_prompt=True. OK.

Now, an important check: `CommandSpec.__post_init__` forbids "\r" or "\n" in line. `_flatten_quoted_lines` lines come from split so no \n. But `lines[-1] += '"'` for SetValue — if the value's last line already ends with `"`? e.g. value `hello\nworld"` → lines = ["hello", 'world"'] → lines[-1] += '"' → 'world""'. Hmm, SetValue.flatten: `lines = str(self.value).strip().splitlines()`; lines[0] = f'set {field} "{lines[0]}'; lines[-1] += '"'. If value ends with a quote, double quote. Pre-existing behavior? Base: old code did the same (f'{lines[-1]}"'). So pre-existing semantics; unchanged. Not a finding.

Now — the `closes_scope` property: `not self.continuation and self.line.strip().lower() in {"next", "end"}`. What about `CommandSpec("end")` used for abort/reset? `_restore_replay_context` uses "abort". OK. But what about cleanup blocks ending with "end" — also closes_scope → mandatory failure check. Documented.

Now — one more potential issue: `_validate_completion` now checks closes_scope commands for failure, but only if output was captured. closes_scope commands get capture via `on_output`. But `on_output` is only invoked when the commander receives unmatched output. If the entire response "Command fail. Return code -61.\r\nfw (port1)#\r\n" arrives in ONE read and the CMD_PROMPT match consumes through "#", the bytes BEFORE the match end (the "Command fail..." text) — are they in attempt.output? The expect returns `consumed = buffer[:match.end()]` as Data (no discard callback needed, consumed). Then driver: `if output and not matched:` — matched=True, so on_output NOT called with it! Then `_process_state(state, output)` → commander.on_state(CMD_PROMPT, output) → on_output(output) inside on_state → `if self._inflight: self._call_feature(self._inflight.on_output, output)` → attempt captures `consumed` (which includes failure text + prompt). Yes! on_state calls on_output(output) before completing inflight. So attempt.output includes the failure text even when it arrives in the same read as the prompt. Good — that's how the existing capture_output mechanism works.

Now — but what about `_complete_inflight`'s context-loss check happening before on_output? No: on_state calls on_output(output) early (line 292) before inflight completion (line 315-319). Good.

Now check `test_common_scope_errors` `test_closing_failure_cannot_be_disabled_or_replayed`: capture=False case — the failure text chunks are passed as Data via commander.on_output directly (simulating). attempt.on_output captures since closes_scope → True. Then prompt(commander, "interface") completes inflight → validate raises. For best_effort: handle_work_error → continue_on_error → recover → feature_errors. And `writes == [close + "\r", "get status\r"]` — the feature is skipped and following feature runs. But note context: prompt(commander, "interface") sets _prompt_context=("interface",)... The following feature's block "get status" dispatched at context ("interface",). Not relevant.

Hmm wait — in that test, after the closing failure, `_complete_inflight` → context changed? before=None (dispatch happened before any prompt context — the test calls prompt(commander, "port1") first... wait: `self.prompt(commander, "port1")` — that's the first on_state; at that point `_active_feature` is None → _dispatch_next → activate feature → submit block → block_prompt_context = ("port1",). Then dispatch "next" with prompt_context_before=("port1",). Then failure chunks. Then `self.prompt(commander, "interface")` → on_state: CMD_PROMPT → _extract context ("interface",) → _prompt_context=("interface",). Then inflight completes: context changed ("port1",)→("interface",) and `_command_may_change_context("next")` → True → NOT context loss. Then validate → failure → handle_work_error. Good.

For the non-best-effort case: `_handle_work_error` raises → propagates from on_state → process_state in real tests. In this unit test, they call commander.on_state directly → assertRaises around the prompt call. ✓.

Now, `_handle_work_error` raising inside `_complete_inflight` — inflight already cleared. And in `_handle_session_loss` cleanup retry limit — raise via _handle_work_error.

Now let's examine `test_common_recovery.make_commander` — FOSCommander(terminal, MagicMock(), continue_on_error) with terminal MagicMock. `prompt()` calls commander.on_state(CMD_PROMPT, Data(...)). The Data has discard_callback None. on_state → _extract context from "FGT-VM64-KVM-NSVHDM (port1) (Interim)#" → context ("port1", "Interim"). OK.

Wait — the context extraction: `CLI_PROMPT_CONTEXT_PATTERN` requires the line to END after `[#$]` with optional \r. "FGT-VM64-KVM-NSVHDM (port1) (Interim)#" — the hostname regex BOOTSTRAP_HOSTNAME_REGEX matches "FGT-VM64-KVM-NSVHDM"? GENERIC_HOSTNAME_REGEX `[A-Za-z0-9_.-]+` matches. Then context `(?:[ \t]+\([^)]+\))*` matches " (port1) (Interim)". Then `[#$]`. ✓.

But note the first alternative in BOOTSTRAP_HOSTNAME_REGEX is GENERIC which matches any hostname — fine.

Now — one concern: `_extract_prompt_context` uses `matches[-1]` (last match in output). Output for a CMD_PROMPT state may contain echo lines of previous prompts (e.g. "fw (port1) # set ip ...\r\nfw (port1) #"). The last prompt line is the current one. OK.

But there's a trap: the CMD_PROMPT_ECHO state — output has trailing text after the prompt; the CMD_PROMPT pattern requires end-of-line so echo lines won't match CMD_PROMPT pattern; they match CMD_PROMPT_ECHO. on_prompt_echo doesn't update context. Then the same line later (after the echo consumed) matches CMD_PROMPT? The echo consumed through the trailing content; the remaining is the command output. Fine.

Now the diff to `test_common_stack_boundaries.state_case`: `initial_prompt=b"fw (global) #" if state == CMD_PROMPT_ECHO else b"fw #"`. Hmm, why? Because on_prompt_echo → on_output(output) — the echo Data passed to commander.on_output... with the new timeout semantics? Not obviously related. Whatever, tests adjusted.

Now — a deeper look at a possible real bug: `_dispatch_next` is now gated on `_pending_feature_error is not None`. Consider `_recover_feature_error` called from `_handle_context_loss` path (in `_complete_inflight`): after `_handle_work_error` (continue_on_error=True), `_recover_feature_error()` → continue_after_error → clears everything → `_dispatch_next()`. But `_dispatch_next` checks `_pending_feature_error is not None` — it was set to None inside _recover_feature_error before calling _dispatch_next. ✓ (line 112: `self._pending_feature_error = None` then `_dispatch_next`).

Wait, `continue_after_error` returns None if `not at_command_prompt or self._ready` or no active feature. In `_recover_feature_error`, at_command_prompt=True. If `_ready` (startup complete) → returns None → error stays pending → tick() returns early → features stall? For runtime features after startup... `enqueue_runtime_features` sets _ready=False. Hmm, if an error occurs when _ready is True and pending error set... `_recover_feature_error` would never clear → `_dispatch_next` blocked forever → but also `tick` blocked. This is pre-existing behavior though (old code: `_recover_feature_error` same structure). Actually old code `_call_feature` set _pending_feature_error too. Same. Not introduced.

Now, an important new-behavior check: `_complete_inflight` — when validation raises and `continue_on_error=True`, `_handle_work_error` sets pending error and `_recover_feature_error()` runs. But `continue_after_error` clears `self._active_feature` etc. But it does NOT clear `self._recovery_retries`? It clears `_cleanup_retries` but not `_recovery_retries`. `_recovery_retries` is reset on `submit_block`. Fine.

Now — one more: `_restore_replay_context` dispatches `CommandSpec("abort", suppress_output=True)` via `_dispatch_command(spec)` with block_index=None. `retry_count` computed from `_recovery_retries.get(None, 0)`. Harmless.

But: `_dispatch_command` is called directly (not via `_dispatch_next`) — before that, `_inflight` must be None. In `_restore_replay_context` called from `_dispatch_next` top — inflight None. ✓. Also from `_complete_inflight`? No.

Wait — there's a subtle re-entrancy: `_complete_inflight` → `_handle_context_loss` → `_restart_active_block` sets pending → then `self._dispatch_next()` → `_restore_replay_context` → may dispatch abort → `_dispatch_command` sets `_inflight`. OK.

Now — `submit_block` resets `_recovery_retries = {}` — but what if a feature submits a new block while a context-loss replay target is set? submit_block clears `_replay_context_target`. OK.

Now — the cleanup path in `_handle_session_loss`: `self._cleanup_retries[id(attempt.spec)] = retries + 1; self._cleanup.appendleft(attempt.spec)`. Then when the retried cleanup command completes successfully: `_complete_inflight` → `if self._in_cleanup: self._cleanup_retries.pop(id(attempt.spec), None)`. But note the pop happens on ANY successful completion — including the FIRST (non-retried) attempt, popping an entry that isn't there (pop with default). Fine.

Now let me check `launch.py` for the KernelPanicError handling context and also `continue_after_error` usage — the driver's process_state exceptions. Read the relevant part of launch.py.

Also need to check `fos_healthcheck.py` / `startup_config` interplay? startup_config parse errors: `ApplyStartupConfig.__init__` calls parse_startup_config which may raise ValueError for malformed config — where is that caught? It's constructed in the features list in launch.py presumably at build time — a raise there would crash the launcher. Previously, malformed structure also raised (line 100 etc. pre-existing). New: unterminated quote raises ValueError — new failure mode documented in README ("fails startup on malformed structure or unterminated quoted strings"). OK documented.

Now check the tests' imports: test_common_admin_credentials imports `from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection`. Does test_common_stack_parsing define RecordingFeature and SerialConnection at module level? The diff shows SerialConnection in test_common_stack_parsing (context lines around line 40). RecordingFeature — the new test test_aborted_interface_edit_recovers_through_serial_driver uses `RecordingFeature(commander, "management", [...])` and `self.make_stack(configured, responses)` — must be defined in that file. Let me read the head of test_common_stack_parsing.py and test_common_stack_boundaries.py, plus the test files fully to check consistency (e.g., helper methods used exist).

Also verify `test_common_recovery.py` uses `StaticFeature` imported from features.base — imported ✓ (line: `from fortinet.common.features.base import Feature, StaticFeature`).

In test_common_recovery, `RecordingFeature.__init__` calls `super().__init__(None, commander, "management")`. And `make_commander(..., ip_command=IP_COMMAND if explicit_policy else spec, ...)`. Hmm: `make_commander(*, ip_command=IP_COMMAND, ..., context_action=None)`. In test_feature_can_decline_replay_without_running_session_loss_loss: explicit_policy False → ip_command=spec (a CommandSpec with session_loss=CONTINUE), context_action=None → feature uses spec.context_loss = FAIL (derived). explicit_policy True → ip_command=IP_COMMAND (plain string), context_action=FAIL → RecordingFeature returns FAIL. Both decline. ✓.

Now, let me also check `test_common_recovery.test_partial_scope_is_aborted_once_before_replay`: prompt(commander, "interface") after enter_interface — context before=("port1","Interim")? Wait `enter_interface` prompts "interface" then "port1" contexts; prompt() context strings: "FGT-VM64-KVM-NSVHDM (port1) (Interim)#". So context after IP command = ("port1", "Interim"). Then prompt(commander, "interface") → context ("interface", "Interim") → changed → context loss → restart → target = _block_prompt_context. What was _block_prompt_context? submit_block at activate() — activate called from _dispatch_next after the first prompt(commander) which set _prompt_context=(). So target=(). Current context ("interface","Interim") ≠ () → abort dispatched. writes[-1]=="abort\r" ✓. Then prompt(commander) → abort completes at CMD_PROMPT (context ()) → _in_context_reset → dispatch_next → restore: context == target → True → replay "config system interface". ✓.

Hmm — wait, there's a subtle issue with `_restore_replay_context` when `target == ()` but the current prompt context is `()` and there's NO actual open scope: fine.

But consider: target = () but the session loss left us at a prompt inside a scope, e.g. context ("interface",). abort exits one scope level → ("Interim",)? Hmm, abort in FortiOS exits the current config scope to its parent. If the block opened "config system interface" then "edit port1" and we're at ("port1","Interim"), abort returns to ("interface","Interim") — still not target (). Then `_context_reset_attempted` True → error "Unable to restore CLI context". Hmm! Is that right? The test test_partial_scope... has before=("port1","Interim"), after=("interface","Interim") → abort from ("interface","Interim") returns to ("Interim",)? The test then prompts(commander) with no context → () → matches target. But in reality, if you're at ("interface","Interim") and abort, you'd go to ("Interim",) — the test's next prompt is context None (top-level). FortiOS prompts show VDOM context "(Interim)" typically. The test's plain prompt is "FGT...#" without (Interim) — meaning context (). Hmm, so the tests model top-level as (). In test_common_stack_parsing, the login prompt is "fw (Interim)#" → context ("Interim",). So contexts include VDOM. Whatever — tests are consistent within themselves.

But is abort-from-"interface"-context → top-level correct in real FortiOS? `abort` within `config system interface` returns to the parent (root). Yes, abort ends the current config scope. If the lost context was deeper (we were in edit port1, context moved to interface), abort from interface → top. OK plausible.

Now the `test_failed_context_reset_does_not_loop`: after abort, prompt(commander, "interface") again → context ("interface","Interim") ≠ target () and `_context_reset_attempted` True → error. ✓ abort count 1.

OK. Now let me read the test files fully, plus pki.py diff region, launch.py, and the READMEs. Also verify `trace` level change doesn't break something else. And check `RecordingFeature` in test_common_stack_parsing head and `make_stack` signature.

Let me read the remaining head test files and pki.py diff context, launch.py section.
Now let me read the test files and remaining source files.
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_stack_parsing.py"
}

Output

<path>/source/head/fortinet/tests/test_common_stack_parsing.py</path>
<type>file</type>
<content>
1: """End-to-end parsing from a serial connection through the FortiOS commander."""
2: 
3: import queue
4: import sys
5: import unittest
6: from pathlib import Path
7: from unittest.mock import MagicMock
8: 
9: REPO_ROOT = Path(__file__).resolve().parents[2]
10: sys.path.insert(0, str(REPO_ROOT))
11: 
12: from fortinet.common.cli_commands import (  # noqa: E402
13:     CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,
14: )
15: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
16: from fortinet.common.features.base import Feature  # noqa: E402
17: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
18: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
19: from fortinet.common.terminal import Terminal  # noqa: E402
20: 
21: 
22: class SerialConnection:
23:     """A serial-like connection that answers each write with a byte stream."""
24: 
25:     def __init__(self, responses):
26:         self._incoming = queue.Queue()
27:         self._responses = responses
28:         self.writes = []
29:         self.closed = False
30:         self._incoming.put(b"fw login:\r\n")
31: 
32:     def read_very_eager(self):
33:         try:
34:             return self._incoming.get_nowait()
35:         except queue.Empty:
36:             return b""
37: 
38:     def write(self, data):
39:         data = bytes(data)
40:         self.writes.append(data)
41:         response = self._responses.get(data)
42:         if callable(response):
43:             response = response()
44:         if response:
45:             chunks = response if isinstance(response, (tuple, list)) else (response,)
46:             for chunk in chunks:
47:                 if chunk:
48:                     self._incoming.put(bytes(chunk))
49: 
50:     def close(self):
51:         self.closed = True
52: 
53:     def suppress_output(self):
54:         from contextlib import nullcontext
55:         return nullcontext()
56: 
57: 
58: class RecordingFeature(Feature):
59:     def __init__(self, commander, name, commands):
60:         super().__init__(None, commander, name)
61:         self.commands = commands
62:         self.executed = []
63:         self.dispatched = []
64: 
65:     def activate(self):
66:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))
67: 
68:     def on_command_dispatched(self, attempt):
69:         super().on_command_dispatched(attempt)
70:         self.dispatched.append(attempt)
71: 
72:     def on_command_executed(self, attempt, state):
73:         self.executed.append((attempt.spec.line, bytes(attempt.output), state))
74: 
75: 
76: class FullStackParsingTests(unittest.TestCase):
77:     def make_stack(self, features, responses, *, allow_credential_recovery=False):
78:         logger = MagicMock()
79:         connection = SerialConnection(responses)
80:         terminal = Terminal(connection, logger, default_wait="fw #")
81:         commander = FOSCommander(terminal, logger)
82:         commander.start(features(commander))
83:         driver = FOSCliDriver(
84:             terminal=terminal,
85:             commander=commander,
86:             credentials=Credentials("admin", "secret"),
87:             logger=logger,
88:             bootstrap_password="Bootstrap1!",
89:             activate_blank_credentials=MagicMock(),
90:             activate_bootstrap_credentials=MagicMock(),
91:             allow_credential_recovery=allow_credential_recovery,
92:         )
93:         return connection, terminal, commander, driver
94: 
95:     def test_login_command_echo_multiline_output_and_continuation(self):
96:         result = b"".join([
97:             b"fw # show full-configuration system dns\r\n",
98:             b"config system dns\r\n",
99:             b"    set protocol dot\r\n",
100:             b"    set primary 9.9.9.9\r\n",
101:             b"end\r\n",
102:             b"fw #\r\n",
103:         ])
104:         responses = {
105:             b"admin\r": b"Password:",
106:             b"secret\r": b"Welcome!\r\nfw #\r\n",
107:             b"show full-configuration system dns\r": result,
108:             b'set comment "first line\r': b">\r\n",
109:             b"second line\r": b">\r\n",
110:             b'third line"\r': b"fw #\r\n",
111:         }
112:         features = []
113: 
114:         def configured(commander):
115:             inspect = RecordingFeature(commander, "inspect", [
116:                 CommandSpec("show full-configuration system dns", capture_output=True),
117:             ])
118:             multiline = RecordingFeature(commander, "multiline", [
119:                 SetValue("comment", "first line\nsecond line\nthird line"),
120:             ])
121:             features.extend([inspect, multiline])
122:             return features
123: 
124:         connection, terminal, commander, driver = self.make_stack(configured, responses)
125:         driver.process_state()
126: 
127:         self.assertTrue(commander.ready)
128:         self.assertTrue(commander.startup_complete)
129:         self.assertTrue(all(feature.completed for feature in features))
130:         self.assertTrue(connection.closed)
131:         self.assertEqual(connection.writes, [
132:             b"admin\r",
133:             b"secret\r",
134:             b"show full-configuration system dns\r",
135:             b'set comment "first line\r',
136:             b"second line\r",
137:             b'third line"\r',
138:         ])
139:         self.assertEqual(len(features[0].executed), 1)
140:         captured = features[0].executed[0][1]
141:         self.assertIn(b"set protocol dot", captured)
142:         self.assertIn(b"set primary 9.9.9.9", captured)
143:         self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)
144:         self.assertEqual(
145:             [entry[2] for entry in features[1].executed],
146:             [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],
147:         )
148:         self.assertTrue(all(attempt.output for attempt in features[1].dispatched))
149:         self.assertEqual(bytes(terminal._buffer), b"")
150: 
151:     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):
152:         responses = {
153:             b"admin\r": b"Password:",
154:             b"secret\r": b"Welcome!\r\nfw (global) #\r\n",
155:             b"get system status\r": (
156:                 b"fw (global) # get system status\r\n"
157:                 b"Version: FortiGate-VM64 v7.4.2,build2571\r\n"
158:                 b"--More--\r\n"
159:                 b"Serial-Number: FGVMTEST\r\n"
160:                 b"fw (global) #\r\n"
161:             ),
162:             b" \r": b"fw (global) #\r\n",
163:         }
164:         feature_ref = []
165: 
166:         class PagerFeature(RecordingFeature):
167:             def on_command_executed(self, attempt, state):
168:                 super().on_command_executed(attempt, state)
169:                 self.commander.feature_complete(self)
170: 
171:         def configured(commander):
172:             feature = PagerFeature(commander, "status", [
173:                 CommandSpec("get system status", capture_output=True),
174:             ])
175:             feature_ref.append(feature)
176:             return [feature]
177: 
178:         connection, _terminal, commander, driver = self.make_stack(configured, responses)
179:         driver.process_state()
180: 
181:         feature = feature_ref[0]
182:         self.assertTrue(commander.ready)
183:         self.assertTrue(feature.completed)
184:         self.assertEqual(connection.writes, [
185:             b"admin\r", b"secret\r", b"get system status\r", b" ",
186:         ])
187:         captured = feature.executed[0][1]
188:         self.assertIn(b"FortiGate-VM64 v7.4.2,build2571", captured)
189:         self.assertIn(b"Serial-Number: FGVMTEST", captured)
190:         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)
191:         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)
192: 
193:     def test_aborted_interface_edit_recovers_through_serial_driver(self):
194:         ip_responses = iter([
195:             b"abort\r\nfw (Interim)#\r\n",
196:             b"fw (port1) (Interim)#\r\n",
197:         ])
198:         responses = {
199:             b"admin\r": b"Password:",
200:             b"secret\r": b"Welcome!\r\nfw (Interim)#\r\n",
201:             b"config system interface\r": b"fw (interface) (Interim)#\r\n",
202:             b"edit port1\r": b"fw (port1) (Interim)#\r\n",
203:             b"set ip 10.0.52.4/24\r": lambda: next(ip_responses),
204:             b"set allowaccess ping https ssh http\r": b"fw (port1) (Interim)#\r\n",
205:             b"next\r": b"fw (interface) (Interim)#\r\n",
206:             b"end\r": b"fw (Interim)#\r\n",
207:         }
208:         feature_ref = []
209: 
210:         def configured(commander):
211:             feature = RecordingFeature(commander, "management", [
212:                 ConfigBlock("system interface", [EditBlock("port1", [
213:                     "set ip 10.0.52.4/24", "set allowaccess ping https ssh http",
214:                 ])]),
215:             ])
216:             feature_ref.append(feature)
217:             return [feature]
218: 
219:         connection, terminal, commander, driver = self.make_stack(configured, responses)
220:         try:
221:             driver.process_state()
222:             self.assertTrue(commander.ready)
223:             self.assertTrue(feature_ref[0].completed)
224:             self.assertEqual(connection.writes, [
225:                 b"admin\r", b"secret\r",
226:                 b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
227:                 b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
228:                 b"set allowaccess ping https ssh http\r", b"next\r", b"end\r",
229:             ])
230:         finally:
231:             terminal.close()
232: 
233:     def test_failed_next_ejects_before_end_through_serial_driver(self):
234:         responses = {
235:             b"admin\r": b"Password:",
236:             b"secret\r": b"Welcome!\r\nfw #\r\n",
237:             b"config system interface\r": b"fw (interface)#\r\n",
238:             b"edit port1\r": b"fw (port1)#\r\n",
239:             b"set unsupported 1\r": b"Command fail. Return code -61.\r\nfw (port1)#\r\n",
240:             b"next\r": (
241:                 b"Command fa", b"il. Return code -5.\r\nfw (port1)#\r\n",
242:             ),
243:         }
244:         feature_ref = []
245: 
246:         def configured(commander):
247:             feature = RecordingFeature(commander, "management", [
248:                 ConfigBlock("system interface", [EditBlock("port1", ["set unsupported 1"])]),
249:             ])
250:             feature_ref.append(feature)
251:             return [feature]
252: 
253:         connection, terminal, commander, driver = self.make_stack(configured, responses)
254:         try:
255:             with self.assertRaisesRegex(RuntimeError, "'next'.*return code -5"):
256:                 driver.process_state()
257:             self.assertEqual(connection.writes, [
258:                 b"admin\r", b"secret\r", b"config system interface\r",
259:                 b"edit port1\r", b"set unsupported 1\r", b"next\r",
260:             ])
261:             self.assertFalse(feature_ref[0].completed)
262:             self.assertFalse(commander.ready)
263:         finally:
264:             terminal.close()
265: 
266: 
267: if __name__ == "__main__":
268:     unittest.main()

(End of file - total 268 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d39955001EOpO0jE4vUa1iV",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d182710012PgOW4K94onaxs",
  "callID": "call_07e0b38cdb794dbe8340f5ce",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_stack_parsing.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_stack_parsing.py</path>\n<type>file</type>\n<content>\n1: \"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n2: \n3: import queue\n4: import sys\n5: import unittest\n6: from pathlib import Path\n7: from unittest.mock import MagicMock\n8: \n9: REPO_ROOT = Path(__file__).resolve().parents[2]\n10: sys.path.insert(0, str(REPO_ROOT))\n11: \n12: from fortinet.common.cli_commands import (  # noqa: E402\n13:     CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n14: )\n15: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n16: from fortinet.common.features.base import Feature  # noqa: E402\n17: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n18: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n19: from fortinet.common.terminal import Terminal  # noqa: E402\n20: \n21: \n22: class SerialConnection:\n23:     \"\"\"A serial-like connection that answers each write with a byte stream.\"\"\"\n24: \n25:     def __init__(self, responses):\n26:         self._incoming = queue.Queue()\n27:         self._responses = responses\n28:         self.writes = []\n29:         self.closed = False\n30:         self._incoming.put(b\"fw login:\\r\\n\")\n31: \n32:     def read_very_eager(self):\n33:         try:\n34:             return self._incoming.get_nowait()\n35:         except queue.Empty:\n36:             return b\"\"\n37: \n38:     def write(self, data):\n39:         data = bytes(data)\n40:         self.writes.append(data)\n41:         response = self._responses.get(data)\n42:         if callable(response):\n43:             response = response()\n44:         if response:\n45:             chunks = response if isinstance(response, (tuple, list)) else (response,)\n46:             for chunk in chunks:\n47:                 if chunk:\n48:                     self._incoming.put(bytes(chunk))\n49: \n50:     def close(self):\n51:         self.closed = True\n52: \n53:     def suppress_output(self):\n54:         from contextlib import nullcontext\n55:         return nullcontext()\n56: \n57: \n58: class RecordingFeature(Feature):\n59:     def __init__(self, commander, name, commands):\n60:         super().__init__(None, commander, name)\n61:         self.commands = commands\n62:         self.executed = []\n63:         self.dispatched = []\n64: \n65:     def activate(self):\n66:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n67: \n68:     def on_command_dispatched(self, attempt):\n69:         super().on_command_dispatched(attempt)\n70:         self.dispatched.append(attempt)\n71: \n72:     def on_command_executed(self, attempt, state):\n73:         self.executed.append((attempt.spec.line, bytes(attempt.output), state))\n74: \n75: \n76: class FullStackParsingTests(unittest.TestCase):\n77:     def make_stack(self, features, responses, *, allow_credential_recovery=False):\n78:         logger = MagicMock()\n79:         connection = SerialConnection(responses)\n80:         terminal = Terminal(connection, logger, default_wait=\"fw #\")\n81:         commander = FOSCommander(terminal, logger)\n82:         commander.start(features(commander))\n83:         driver = FOSCliDriver(\n84:             terminal=terminal,\n85:             commander=commander,\n86:             credentials=Credentials(\"admin\", \"secret\"),\n87:             logger=logger,\n88:             bootstrap_password=\"Bootstrap1!\",\n89:             activate_blank_credentials=MagicMock(),\n90:             activate_bootstrap_credentials=MagicMock(),\n91:             allow_credential_recovery=allow_credential_recovery,\n92:         )\n93:         return connection, terminal, commander, driver\n94: \n95:     def test_login_command_echo_multiline_output_and_continuation(self):\n96:         result = b\"\".join([\n97:             b\"fw # show full-configuration system dns\\r\\n\",\n98:             b\"config system dns\\r\\n\",\n99:             b\"    set protocol dot\\r\\n\",\n100:             b\"    set primary 9.9.9.9\\r\\n\",\n101:             b\"end\\r\\n\",\n102:             b\"fw #\\r\\n\",\n103:         ])\n104:         responses = {\n105:             b\"admin\\r\": b\"Password:\",\n106:             b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n107:             b\"show full-configuration system dns\\r\": result,\n108:             b'set comment \"first line\\r': b\">\\r\\n\",\n109:             b\"second line\\r\": b\">\\r\\n\",\n110:             b'third line\"\\r': b\"fw #\\r\\n\",\n111:         }\n112:         features = []\n113: \n114:         def configured(commander):\n115:             inspect = RecordingFeature(commander, \"inspect\", [\n116:                 CommandSpec(\"show full-configuration system dns\", capture_output=True),\n117:             ])\n118:             multiline = RecordingFeature(commander, \"multiline\", [\n119:                 SetValue(\"comment\", \"first line\\nsecond line\\nthird line\"),\n120:             ])\n121:             features.extend([inspect, multiline])\n122:             return features\n123: \n124:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n125:         driver.process_state()\n126: \n127:         self.assertTrue(commander.ready)\n128:         self.assertTrue(commander.startup_complete)\n129:         self.assertTrue(all(feature.completed for feature in features))\n130:         self.assertTrue(connection.closed)\n131:         self.assertEqual(connection.writes, [\n132:             b\"admin\\r\",\n133:             b\"secret\\r\",\n134:             b\"show full-configuration system dns\\r\",\n135:             b'set comment \"first line\\r',\n136:             b\"second line\\r\",\n137:             b'third line\"\\r',\n138:         ])\n139:         self.assertEqual(len(features[0].executed), 1)\n140:         captured = features[0].executed[0][1]\n141:         self.assertIn(b\"set protocol dot\", captured)\n142:         self.assertIn(b\"set primary 9.9.9.9\", captured)\n143:         self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)\n144:         self.assertEqual(\n145:             [entry[2] for entry in features[1].executed],\n146:             [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],\n147:         )\n148:         self.assertTrue(all(attempt.output for attempt in features[1].dispatched))\n149:         self.assertEqual(bytes(terminal._buffer), b\"\")\n150: \n151:     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n152:         responses = {\n153:             b\"admin\\r\": b\"Password:\",\n154:             b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n155:             b\"get system status\\r\": (\n156:                 b\"fw (global) # get system status\\r\\n\"\n157:                 b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n158:                 b\"--More--\\r\\n\"\n159:                 b\"Serial-Number: FGVMTEST\\r\\n\"\n160:                 b\"fw (global) #\\r\\n\"\n161:             ),\n162:             b\" \\r\": b\"fw (global) #\\r\\n\",\n163:         }\n164:         feature_ref = []\n165: \n166:         class PagerFeature(RecordingFeature):\n167:             def on_command_executed(self, attempt, state):\n168:                 super().on_command_executed(attempt, state)\n169:                 self.commander.feature_complete(self)\n170: \n171:         def configured(commander):\n172:             feature = PagerFeature(commander, \"status\", [\n173:                 CommandSpec(\"get system status\", capture_output=True),\n174:             ])\n175:             feature_ref.append(feature)\n176:             return [feature]\n177: \n178:         connection, _terminal, commander, driver = self.make_stack(configured, responses)\n179:         driver.process_state()\n180: \n181:         feature = feature_ref[0]\n182:         self.assertTrue(commander.ready)\n183:         self.assertTrue(feature.completed)\n184:         self.assertEqual(connection.writes, [\n185:             b\"admin\\r\", b\"secret\\r\", b\"get system status\\r\", b\" \",\n186:         ])\n187:         captured = feature.executed[0][1]\n188:         self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n189:         self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n190:         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n191:         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n192: \n193:     def test_aborted_interface_edit_recovers_through_serial_driver(self):\n194:         ip_responses = iter([\n195:             b\"abort\\r\\nfw (Interim)#\\r\\n\",\n196:             b\"fw (port1) (Interim)#\\r\\n\",\n197:         ])\n198:         responses = {\n199:             b\"admin\\r\": b\"Password:\",\n200:             b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n201:             b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n202:             b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n203:             b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n204:             b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n205:             b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n206:             b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n207:         }\n208:         feature_ref = []\n209: \n210:         def configured(commander):\n211:             feature = RecordingFeature(commander, \"management\", [\n212:                 ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n213:                     \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n214:                 ])]),\n215:             ])\n216:             feature_ref.append(feature)\n217:             return [feature]\n218: \n219:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n220:         try:\n221:             driver.process_state()\n222:             self.assertTrue(commander.ready)\n223:             self.assertTrue(feature_ref[0].completed)\n224:             self.assertEqual(connection.writes, [\n225:                 b\"admin\\r\", b\"secret\\r\",\n226:                 b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n227:                 b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n228:                 b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n229:             ])\n230:         finally:\n231:             terminal.close()\n232: \n233:     def test_failed_next_ejects_before_end_through_serial_driver(self):\n234:         responses = {\n235:             b\"admin\\r\": b\"Password:\",\n236:             b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n237:             b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n238:             b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n239:             b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n240:             b\"next\\r\": (\n241:                 b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n242:             ),\n243:         }\n244:         feature_ref = []\n245: \n246:         def configured(commander):\n247:             feature = RecordingFeature(commander, \"management\", [\n248:                 ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n249:             ])\n250:             feature_ref.append(feature)\n251:             return [feature]\n252: \n253:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n254:         try:\n255:             with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n256:                 driver.process_state()\n257:             self.assertEqual(connection.writes, [\n258:                 b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n259:                 b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n260:             ])\n261:             self.assertFalse(feature_ref[0].completed)\n262:             self.assertFalse(commander.ready)\n263:         finally:\n264:             terminal.close()\n265: \n266: \n267: if __name__ == \"__main__\":\n268:     unittest.main()\n\n(End of file - total 268 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_stack_parsing.py",
    "metadata": {
      "preview": "\"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n\nimport queue\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n)\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_stack_parsing.py",
        "text": "\"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n\nimport queue\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n)\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\n\n\nclass SerialConnection:\n    \"\"\"A serial-like connection that answers each write with a byte stream.\"\"\"\n\n    def __init__(self, responses):\n        self._incoming = queue.Queue()\n        self._responses = responses\n        self.writes = []\n        self.closed = False\n        self._incoming.put(b\"fw login:\\r\\n\")\n\n    def read_very_eager(self):\n        try:\n            return self._incoming.get_nowait()\n        except queue.Empty:\n            return b\"\"\n\n    def write(self, data):\n        data = bytes(data)\n        self.writes.append(data)\n        response = self._responses.get(data)\n        if callable(response):\n            response = response()\n        if response:\n            chunks = response if isinstance(response, (tuple, list)) else (response,)\n            for chunk in chunks:\n                if chunk:\n                    self._incoming.put(bytes(chunk))\n\n    def close(self):\n        self.closed = True\n\n    def suppress_output(self):\n        from contextlib import nullcontext\n        return nullcontext()\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):\n        super().__init__(None, commander, name)\n        self.commands = commands\n        self.executed = []\n        self.dispatched = []\n\n    def activate(self):\n        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n\n    def on_command_dispatched(self, attempt):\n        super().on_command_dispatched(attempt)\n        self.dispatched.append(attempt)\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append((attempt.spec.line, bytes(attempt.output), state))\n\n\nclass FullStackParsingTests(unittest.TestCase):\n    def make_stack(self, features, responses, *, allow_credential_recovery=False):\n        logger = MagicMock()\n        connection = SerialConnection(responses)\n        terminal = Terminal(connection, logger, default_wait=\"fw #\")\n        commander = FOSCommander(terminal, logger)\n        commander.start(features(commander))\n        driver = FOSCliDriver(\n            terminal=terminal,\n            commander=commander,\n            credentials=Credentials(\"admin\", \"secret\"),\n            logger=logger,\n            bootstrap_password=\"Bootstrap1!\",\n            activate_blank_credentials=MagicMock(),\n            activate_bootstrap_credentials=MagicMock(),\n            allow_credential_recovery=allow_credential_recovery,\n        )\n        return connection, terminal, commander, driver\n\n    def test_login_command_echo_multiline_output_and_continuation(self):\n        result = b\"\".join([\n            b\"fw # show full-configuration system dns\\r\\n\",\n            b\"config system dns\\r\\n\",\n            b\"    set protocol dot\\r\\n\",\n            b\"    set primary 9.9.9.9\\r\\n\",\n            b\"end\\r\\n\",\n            b\"fw #\\r\\n\",\n        ])\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n            b\"show full-configuration system dns\\r\": result,\n            b'set comment \"first line\\r': b\">\\r\\n\",\n            b\"second line\\r\": b\">\\r\\n\",\n            b'third line\"\\r': b\"fw #\\r\\n\",\n        }\n        features = []\n\n        def configured(commander):\n            inspect = RecordingFeature(commander, \"inspect\", [\n                CommandSpec(\"show full-configuration system dns\", capture_output=True),\n            ])\n            multiline = RecordingFeature(commander, \"multiline\", [\n                SetValue(\"comment\", \"first line\\nsecond line\\nthird line\"),\n            ])\n            features.extend([inspect, multiline])\n            return features\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        driver.process_state()\n\n        self.assertTrue(commander.ready)\n        self.assertTrue(commander.startup_complete)\n        self.assertTrue(all(feature.completed for feature in features))\n        self.assertTrue(connection.closed)\n        self.assertEqual(connection.writes, [\n            b\"admin\\r\",\n            b\"secret\\r\",\n            b\"show full-configuration system dns\\r\",\n            b'set comment \"first line\\r',\n            b\"second line\\r\",\n            b'third line\"\\r',\n        ])\n        self.assertEqual(len(features[0].executed), 1)\n        captured = features[0].executed[0][1]\n        self.assertIn(b\"set protocol dot\", captured)\n        self.assertIn(b\"set primary 9.9.9.9\", captured)\n        self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)\n        self.assertEqual(\n            [entry[2] for entry in features[1].executed],\n            [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],\n        )\n        self.assertTrue(all(attempt.output for attempt in features[1].dispatched))\n        self.assertEqual(bytes(terminal._buffer), b\"\")\n\n    def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n            b\"get system status\\r\": (\n                b\"fw (global) # get system status\\r\\n\"\n                b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n                b\"--More--\\r\\n\"\n                b\"Serial-Number: FGVMTEST\\r\\n\"\n                b\"fw (global) #\\r\\n\"\n            ),\n            b\" \\r\": b\"fw (global) #\\r\\n\",\n        }\n        feature_ref = []\n\n        class PagerFeature(RecordingFeature):\n            def on_command_executed(self, attempt, state):\n                super().on_command_executed(attempt, state)\n                self.commander.feature_complete(self)\n\n        def configured(commander):\n            feature = PagerFeature(commander, \"status\", [\n                CommandSpec(\"get system status\", capture_output=True),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, _terminal, commander, driver = self.make_stack(configured, responses)\n        driver.process_state()\n\n        feature = feature_ref[0]\n        self.assertTrue(commander.ready)\n        self.assertTrue(feature.completed)\n        self.assertEqual(connection.writes, [\n            b\"admin\\r\", b\"secret\\r\", b\"get system status\\r\", b\" \",\n        ])\n        captured = feature.executed[0][1]\n        self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n        self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n        self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n        self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n\n    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n        ip_responses = iter([\n            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n            b\"fw (port1) (Interim)#\\r\\n\",\n        ])\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n        }\n        feature_ref = []\n\n        def configured(commander):\n            feature = RecordingFeature(commander, \"management\", [\n                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n                ])]),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        try:\n            driver.process_state()\n            self.assertTrue(commander.ready)\n            self.assertTrue(feature_ref[0].completed)\n            self.assertEqual(connection.writes, [\n                b\"admin\\r\", b\"secret\\r\",\n                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n            ])\n        finally:\n            terminal.close()\n\n    def test_failed_next_ejects_before_end_through_serial_driver(self):\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n            b\"next\\r\": (\n                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n            ),\n        }\n        feature_ref = []\n\n        def configured(commander):\n            feature = RecordingFeature(commander, \"management\", [\n                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        try:\n            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n                driver.process_state()\n            self.assertEqual(connection.writes, [\n                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n            ])\n            self.assertFalse(feature_ref[0].completed)\n            self.assertFalse(commander.ready)\n        finally:\n            terminal.close()\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 268,
        "totalLines": 268,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716361561,
      "end": 1793716361567
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_terminal_driver.py",
  "limit": 120
}

Output

<path>/source/head/fortinet/tests/test_common_terminal_driver.py</path>
<type>file</type>
<content>
1: """Serial terminal buffering and FortiOS CLI state-machine tests."""
2: 
3: import logging
4: import re
5: import sys
6: import threading
7: import unittest
8: from contextlib import contextmanager
9: from unittest.mock import MagicMock, patch
10: 
11: REPO_ROOT = __import__("pathlib").Path(__file__).resolve().parents[2]
12: sys.path.insert(0, str(REPO_ROOT))
13: 
14: from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402
15: from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402
16: from fortinet.common.fos_cli_driver import (  # noqa: E402
17:     FOSCliDriver,
18:     KernelPanicError,
19: )
20: from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402
21: 
22: 
23: class ByteQueueTests(unittest.TestCase):
24:     def test_put_get_close_timeout_and_failure(self):
25:         queue = _ByteQueue(3)
26:         queue.put(b"abc")
27:         self.assertEqual(queue.get_one(), b"abc")
28:         queue.put(b"def")
29:         self.assertEqual(queue.get(), b"def")
30:         self.assertEqual(queue.get(0), b"")
31:         queue.close()
32:         queue.put(b"ignored")
33:         self.assertEqual(queue.get(), b"")
34:         failed = _ByteQueue(5)
35:         failed.fail(ValueError("read failed"))
36:         with self.assertRaisesRegex(ValueError, "read failed"):
37:             failed.get(0)
38: 
39:     def test_blocked_get_wakes_when_data_arrives(self):
40:         queue = _ByteQueue(10)
41:         result = []
42:         reader = threading.Thread(target=lambda: result.append(queue.get(1)))
43:         reader.start()
44:         queue.put(b"ready")
45:         reader.join(1)
46:         self.assertEqual(result, [b"ready"])
47: 
48: 
49: class TerminalTests(unittest.TestCase):
50:     def terminal_with_data(self, data, limit=100):
51:         terminal = Terminal(MagicMock(), MagicMock())
52:         terminal._buffer_limit = limit
53:         terminal._read_queue = _ByteQueue(limit)
54:         terminal._read_queue.put(data)
55:         terminal._ensure_reader = lambda: None
56:         return terminal
57: 
58:     def test_data_wrapper_and_expect_earliest_match_preserves_tail(self):
59:         view = Data(b"hello")
60:         self.assertTrue(view)
61:         self.assertEqual(len(view), 5)
62:         self.assertIn(b"ell", view)
63:         self.assertEqual(view.decode(), "hello")
64:         self.assertTrue(view.startswith(b"he"))
65:         self.assertEqual(view, b"hello")
66:         terminal = self.terminal_with_data(b"prefix PROMPT trailing")
67:         index, match, output = terminal.expect([b"trailing", b"PROMPT"], timeout=0.1)
68:         self.assertEqual(index, 1)
69:         self.assertEqual(match.group(), b"PROMPT")
70:         self.assertEqual(bytes(output), b"prefix PROMPT")
71:         self.assertEqual(bytes(terminal._buffer), b" trailing")
72:         no_match = self.terminal_with_data(b"abc")
73:         result = no_match.expect([b"never"], timeout=0)
74:         self.assertEqual(result[0:2], (-1, None))
75:         self.assertEqual(bytes(result[2]), b"")
76: 
77:     def test_discard_retained_prefix_and_buffer_limit_error(self):
78:         terminal = self.terminal_with_data(b"output prompt", limit=20)
79:         _, _, _ = terminal.expect([b"prompt"], timeout=0.1)
80:         data = Data(b"output", terminal._discard_prefix)
81:         terminal._buffer = bytearray(b"output trailing")
82:         data.discard(b"output")
83:         self.assertTrue(data.discarded)
84:         self.assertEqual(bytes(terminal._buffer), b" trailing")
85:         data.discard(b"wrong")
86:         terminal._buffer = bytearray(b"123456")
87:         terminal._buffer_limit = 5
88:         with self.assertRaisesRegex(RuntimeError, "exceeded 5"):
89:             terminal._enforce_buffer_limit()
90:         terminal._logger.error.assert_called_once()
91: 
92:     def test_timeout_preserves_partial_token_for_a_later_read(self):
93:         terminal = self.terminal_with_data(b"Login incor")
94:         pattern = rb"(?m)^Login incorrect\r?$"
95:         index, match, output = terminal.expect([pattern], timeout=0.001)
96:         self.assertEqual((index, match), (-1, None))
97:         self.assertEqual(bytes(output), b"Login incor")
98:         # Inspection without discard keeps the partial token, including when
99:         # another wait expires without receiving any more bytes.
100:         _, _, output = terminal.expect([pattern], timeout=0)
101:         self.assertEqual(bytes(output), b"Login incor")
102:         terminal._read_queue.put(b"rect\n")
103:         index, match, output = terminal.expect([pattern], timeout=0.1)
104:         self.assertEqual(index, 0)
105:         self.assertEqual(match.group(), b"Login incorrect")
106:         self.assertEqual(bytes(output), b"Login incorrect")
107:         self.assertEqual(bytes(terminal._buffer), b"\n")
108: 
109:     def test_timeout_inspection_sees_a_token_completed_by_new_input(self):
110:         terminal = self.terminal_with_data(b"Verifying pass")
111:         _, _, output = terminal.expect([b"fw #"], timeout=0.001)
112:         self.assertIsNone(re.search(rb"Verifying password", bytes(output)))
113: 
114:         terminal._read_queue.put(b"word...\n")
115:         _, match, output = terminal.expect([b"fw #"], timeout=0.001)
116:         self.assertIsNone(match)
117:         self.assertIsNotNone(re.search(rb"Verifying password", bytes(output)))
118:         self.assertEqual(bytes(terminal._buffer), b"Verifying password...\n")
119:         output.discard()
120:         self.assertEqual(bytes(terminal._buffer), b"")

(Showing lines 1-120 of 332. Use offset=121 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d399ad0019Eqa4vXVSnLZQ3",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d182710012PgOW4K94onaxs",
  "callID": "call_00ed98a7c44543f3a92adb0d",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_terminal_driver.py",
      "limit": 120
    },
    "output": "<path>/source/head/fortinet/tests/test_common_terminal_driver.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Serial terminal buffering and FortiOS CLI state-machine tests.\"\"\"\n2: \n3: import logging\n4: import re\n5: import sys\n6: import threading\n7: import unittest\n8: from contextlib import contextmanager\n9: from unittest.mock import MagicMock, patch\n10: \n11: REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n12: sys.path.insert(0, str(REPO_ROOT))\n13: \n14: from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n15: from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n16: from fortinet.common.fos_cli_driver import (  # noqa: E402\n17:     FOSCliDriver,\n18:     KernelPanicError,\n19: )\n20: from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n21: \n22: \n23: class ByteQueueTests(unittest.TestCase):\n24:     def test_put_get_close_timeout_and_failure(self):\n25:         queue = _ByteQueue(3)\n26:         queue.put(b\"abc\")\n27:         self.assertEqual(queue.get_one(), b\"abc\")\n28:         queue.put(b\"def\")\n29:         self.assertEqual(queue.get(), b\"def\")\n30:         self.assertEqual(queue.get(0), b\"\")\n31:         queue.close()\n32:         queue.put(b\"ignored\")\n33:         self.assertEqual(queue.get(), b\"\")\n34:         failed = _ByteQueue(5)\n35:         failed.fail(ValueError(\"read failed\"))\n36:         with self.assertRaisesRegex(ValueError, \"read failed\"):\n37:             failed.get(0)\n38: \n39:     def test_blocked_get_wakes_when_data_arrives(self):\n40:         queue = _ByteQueue(10)\n41:         result = []\n42:         reader = threading.Thread(target=lambda: result.append(queue.get(1)))\n43:         reader.start()\n44:         queue.put(b\"ready\")\n45:         reader.join(1)\n46:         self.assertEqual(result, [b\"ready\"])\n47: \n48: \n49: class TerminalTests(unittest.TestCase):\n50:     def terminal_with_data(self, data, limit=100):\n51:         terminal = Terminal(MagicMock(), MagicMock())\n52:         terminal._buffer_limit = limit\n53:         terminal._read_queue = _ByteQueue(limit)\n54:         terminal._read_queue.put(data)\n55:         terminal._ensure_reader = lambda: None\n56:         return terminal\n57: \n58:     def test_data_wrapper_and_expect_earliest_match_preserves_tail(self):\n59:         view = Data(b\"hello\")\n60:         self.assertTrue(view)\n61:         self.assertEqual(len(view), 5)\n62:         self.assertIn(b\"ell\", view)\n63:         self.assertEqual(view.decode(), \"hello\")\n64:         self.assertTrue(view.startswith(b\"he\"))\n65:         self.assertEqual(view, b\"hello\")\n66:         terminal = self.terminal_with_data(b\"prefix PROMPT trailing\")\n67:         index, match, output = terminal.expect([b\"trailing\", b\"PROMPT\"], timeout=0.1)\n68:         self.assertEqual(index, 1)\n69:         self.assertEqual(match.group(), b\"PROMPT\")\n70:         self.assertEqual(bytes(output), b\"prefix PROMPT\")\n71:         self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n72:         no_match = self.terminal_with_data(b\"abc\")\n73:         result = no_match.expect([b\"never\"], timeout=0)\n74:         self.assertEqual(result[0:2], (-1, None))\n75:         self.assertEqual(bytes(result[2]), b\"\")\n76: \n77:     def test_discard_retained_prefix_and_buffer_limit_error(self):\n78:         terminal = self.terminal_with_data(b\"output prompt\", limit=20)\n79:         _, _, _ = terminal.expect([b\"prompt\"], timeout=0.1)\n80:         data = Data(b\"output\", terminal._discard_prefix)\n81:         terminal._buffer = bytearray(b\"output trailing\")\n82:         data.discard(b\"output\")\n83:         self.assertTrue(data.discarded)\n84:         self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n85:         data.discard(b\"wrong\")\n86:         terminal._buffer = bytearray(b\"123456\")\n87:         terminal._buffer_limit = 5\n88:         with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n89:             terminal._enforce_buffer_limit()\n90:         terminal._logger.error.assert_called_once()\n91: \n92:     def test_timeout_preserves_partial_token_for_a_later_read(self):\n93:         terminal = self.terminal_with_data(b\"Login incor\")\n94:         pattern = rb\"(?m)^Login incorrect\\r?$\"\n95:         index, match, output = terminal.expect([pattern], timeout=0.001)\n96:         self.assertEqual((index, match), (-1, None))\n97:         self.assertEqual(bytes(output), b\"Login incor\")\n98:         # Inspection without discard keeps the partial token, including when\n99:         # another wait expires without receiving any more bytes.\n100:         _, _, output = terminal.expect([pattern], timeout=0)\n101:         self.assertEqual(bytes(output), b\"Login incor\")\n102:         terminal._read_queue.put(b\"rect\\n\")\n103:         index, match, output = terminal.expect([pattern], timeout=0.1)\n104:         self.assertEqual(index, 0)\n105:         self.assertEqual(match.group(), b\"Login incorrect\")\n106:         self.assertEqual(bytes(output), b\"Login incorrect\")\n107:         self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n108: \n109:     def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n110:         terminal = self.terminal_with_data(b\"Verifying pass\")\n111:         _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n112:         self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n113: \n114:         terminal._read_queue.put(b\"word...\\n\")\n115:         _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n116:         self.assertIsNone(match)\n117:         self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n118:         self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n119:         output.discard()\n120:         self.assertEqual(bytes(terminal._buffer), b\"\")\n\n(Showing lines 1-120 of 332. Use offset=121 to continue.)\n</content>",
    "title": "source/head/fortinet/tests/test_common_terminal_driver.py",
    "metadata": {
      "preview": "\"\"\"Serial terminal buffering and FortiOS CLI state-machine tests.\"\"\"\n\nimport logging\nimport re\nimport sys\nimport threading\nimport unittest\nfrom contextlib import contextmanager\nfrom unittest.mock import MagicMock, patch\n\nREPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\nfrom fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\nfrom fortinet.common.fos_cli_driver import (  # noqa: E402\n    FOSCliDriver,\n    KernelPanicError,\n)\nfrom fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_terminal_driver.py",
        "text": "\"\"\"Serial terminal buffering and FortiOS CLI state-machine tests.\"\"\"\n\nimport logging\nimport re\nimport sys\nimport threading\nimport unittest\nfrom contextlib import contextmanager\nfrom unittest.mock import MagicMock, patch\n\nREPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\nfrom fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\nfrom fortinet.common.fos_cli_driver import (  # noqa: E402\n    FOSCliDriver,\n    KernelPanicError,\n)\nfrom fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n\n\nclass ByteQueueTests(unittest.TestCase):\n    def test_put_get_close_timeout_and_failure(self):\n        queue = _ByteQueue(3)\n        queue.put(b\"abc\")\n        self.assertEqual(queue.get_one(), b\"abc\")\n        queue.put(b\"def\")\n        self.assertEqual(queue.get(), b\"def\")\n        self.assertEqual(queue.get(0), b\"\")\n        queue.close()\n        queue.put(b\"ignored\")\n        self.assertEqual(queue.get(), b\"\")\n        failed = _ByteQueue(5)\n        failed.fail(ValueError(\"read failed\"))\n        with self.assertRaisesRegex(ValueError, \"read failed\"):\n            failed.get(0)\n\n    def test_blocked_get_wakes_when_data_arrives(self):\n        queue = _ByteQueue(10)\n        result = []\n        reader = threading.Thread(target=lambda: result.append(queue.get(1)))\n        reader.start()\n        queue.put(b\"ready\")\n        reader.join(1)\n        self.assertEqual(result, [b\"ready\"])\n\n\nclass TerminalTests(unittest.TestCase):\n    def terminal_with_data(self, data, limit=100):\n        terminal = Terminal(MagicMock(), MagicMock())\n        terminal._buffer_limit = limit\n        terminal._read_queue = _ByteQueue(limit)\n        terminal._read_queue.put(data)\n        terminal._ensure_reader = lambda: None\n        return terminal\n\n    def test_data_wrapper_and_expect_earliest_match_preserves_tail(self):\n        view = Data(b\"hello\")\n        self.assertTrue(view)\n        self.assertEqual(len(view), 5)\n        self.assertIn(b\"ell\", view)\n        self.assertEqual(view.decode(), \"hello\")\n        self.assertTrue(view.startswith(b\"he\"))\n        self.assertEqual(view, b\"hello\")\n        terminal = self.terminal_with_data(b\"prefix PROMPT trailing\")\n        index, match, output = terminal.expect([b\"trailing\", b\"PROMPT\"], timeout=0.1)\n        self.assertEqual(index, 1)\n        self.assertEqual(match.group(), b\"PROMPT\")\n        self.assertEqual(bytes(output), b\"prefix PROMPT\")\n        self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n        no_match = self.terminal_with_data(b\"abc\")\n        result = no_match.expect([b\"never\"], timeout=0)\n        self.assertEqual(result[0:2], (-1, None))\n        self.assertEqual(bytes(result[2]), b\"\")\n\n    def test_discard_retained_prefix_and_buffer_limit_error(self):\n        terminal = self.terminal_with_data(b\"output prompt\", limit=20)\n        _, _, _ = terminal.expect([b\"prompt\"], timeout=0.1)\n        data = Data(b\"output\", terminal._discard_prefix)\n        terminal._buffer = bytearray(b\"output trailing\")\n        data.discard(b\"output\")\n        self.assertTrue(data.discarded)\n        self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n        data.discard(b\"wrong\")\n        terminal._buffer = bytearray(b\"123456\")\n        terminal._buffer_limit = 5\n        with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n            terminal._enforce_buffer_limit()\n        terminal._logger.error.assert_called_once()\n\n    def test_timeout_preserves_partial_token_for_a_later_read(self):\n        terminal = self.terminal_with_data(b\"Login incor\")\n        pattern = rb\"(?m)^Login incorrect\\r?$\"\n        index, match, output = terminal.expect([pattern], timeout=0.001)\n        self.assertEqual((index, match), (-1, None))\n        self.assertEqual(bytes(output), b\"Login incor\")\n        # Inspection without discard keeps the partial token, including when\n        # another wait expires without receiving any more bytes.\n        _, _, output = terminal.expect([pattern], timeout=0)\n        self.assertEqual(bytes(output), b\"Login incor\")\n        terminal._read_queue.put(b\"rect\\n\")\n        index, match, output = terminal.expect([pattern], timeout=0.1)\n        self.assertEqual(index, 0)\n        self.assertEqual(match.group(), b\"Login incorrect\")\n        self.assertEqual(bytes(output), b\"Login incorrect\")\n        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n\n    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n        terminal = self.terminal_with_data(b\"Verifying pass\")\n        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n\n        terminal._read_queue.put(b\"word...\\n\")\n        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n        self.assertIsNone(match)\n        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n        output.discard()\n        self.assertEqual(bytes(terminal._buffer), b\"\")",
        "lineStart": 1,
        "lineEnd": 120,
        "totalLines": 332,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716361649,
      "end": 1793716361657
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d399bb0017sRczIzXT5HSnr",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d182710012PgOW4K94onaxs",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 89033,
    "input": 1837,
    "output": 58,
    "reasoning": 15202,
    "cache": {
      "read": 71936,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d182710012PgOW4K94onaxs",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716224625,
    "completed": 1793716361662
  },
  "parentID": "msg_1a1d103be001tgPKtIdGJM73lG",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 89033,
    "input": 1837,
    "output": 58,
    "reasoning": 15202,
    "cache": {
      "read": 71936,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 10
compaction
{
  "type": "compaction",
  "id": "prt_1a1d399c00017yi1fH7AKYFpKG",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d399bf001jpJwVa41DjfRYi",
  "auto": true,
  "overflow": false
}
Message metadata
{
  "role": "user",
  "id": "msg_1a1d399bf001jpJwVa41DjfRYi",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716361663
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 11
step-start
{
  "type": "step-start",
  "id": "prt_1a1d3a3ca001xlmqBhAWOmLOG3",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d399d0001Ds1IgkQWIg8sZ9"
}
Reasoning
Summarize this code review conversation following the template.
## Objective
- Perform a source-only, read-only PR review of the snapshot at `/source` (repo `srl-labs/vrnetlab`, head `1c29a33a37619b7547248e3b845130ba1f5f8ad0`, base/mergeBase `11dd16f88e2e5990de1061be498577af6c5d3552`), tracking all 18 changed paths from `diff.txt`, then return the trusted result schema (including disclosed limitation that tests were not executed; manifest indicates snapshot incomplete: true → report incomplete coverage).

## Important Details
- `standards.json` is empty (`[]`) — no rules to apply.
- 18 changed paths (from manifest.json): M `fortinet/common/cli_commands.py`, `common.py`, `features/base.py`, `features/credentials.py`, `features/pki.py`, `features/startup_config.py`, `fos_cli_driver.py`, `fos_commander.py`, `launch.py`, `terminal.py`, `fortigate/README.md`, `fortigate/docker/README.md`, `tests/test_common_stack_boundaries.py`, `tests/test_common_stack_parsing.py`, `tests/test_common_terminal_driver.py`; A `tests/test_common_admin_credentials.py`, `tests/test_common_recovery.py`, `tests/test_common_scope_errors.py`.
- Read tool has permission constraints: bare `/source` directory read denied; must read specific files under `/source/...`.
- PR theme: FortiOS CLI stack rework — new `ContextLossAction` enum (RESTART_BLOCK/FAIL), `CommandSpec.context_loss` + `continuation` fields, prompt-context tracking (`CLI_PROMPT_CONTEXT_PATTERN`, `BOOTSTRAP_HOSTNAME_REGEX`, `PROMPT_CONTEXT_REGEX`), scope-commit failure detection for `closes_scope` commands (`next`/`end` always capture output and are checked for "Command fail. Return code -N"), abort-based context restore with `_context_reset_attempted` bounded retry, `_recovery_retries` keyed by block_index, `_cleanup_retries` keyed by `id(spec)`, terminal `Data` timeout semantics changed to expose the FULL retained buffer (with `received_new_data` flag distinguishing UNKNOWN vs TN_TIMEOUT), env aliasing (`env.py` `get_env` prefers FTNT_* spelling over FOS_*), `TRACE_LEVEL` logging change in terminal, new `KernelPanicError` handling in `launch.py`/driver.
- Initial assistant trace-throughs verified (self-corrected where needed): credentials feature `exit`-logout flow works because "exit" lives in a separate `admin-relogin` block; after end-logout `_handle_session_loss` CONTINUE clears only current block's pending, then `on_block_complete` submits the exit block → exit count 1, newpass count 2 match tests.
- Noted potential concerns under evaluation: (a) features' `on_output` consumers of timeout Data may re-see the full retained buffer repeatedly (duplicate processing risk if they inspect without `discard()`); (b) `_restore_replay_context` with `None` target skips context protection; (c) `id(spec)`-keyed `_cleanup_retries` collision edge case; (d) context-loss check precedes `_validate_completion` in `_complete_inflight` so a failing `next`/`end` that also changes context takes the restart path instead of the "always fatal" failure path.
- env.py is NOT in the changed list but explains FTNT_* precedence behavior tested in `test_common_terminal_driver.py` (`FTNT_TERMINAL_BUFFER_LIMIT_BYTES` beats `FOS_TERMINAL_BUFFER_LIMIT_BYTES`; both `FTNT_LOG_RAW_SERIAL` and `FOS_LOG_RAW_SERIAL` work).
- Read offsets must be used for truncated output; group independent tool calls; use glob/grep for surrounding code.

## Work State
### Completed
- Read `/source/standards.json` (empty) and `/source/manifest.json` (18 changed paths enumerated).
- Read `/source/diff.txt` (both segments, offsets 1 and 1198) — full diff reviewed.
- Read head files: `fortinet/common/cli_commands.py`, `common.py`, `features/credentials.py`, `features/base.py`, `env.py`, `features/startup_config.py`, `fos_commander.py`, `fos_cli_driver.py`, `terminal.py` (all truncated at various points), plus `tests/test_common_stack_parsing.py` and start of `tests/test_common_terminal_driver.py`.
- Verified env.py aliasing semantics resolve the FTNT_*/FOS_* test expectations; verified TRACE_LEVEL logging and prompt-context extraction logic; traced credentials/recovery/context-reset test flows against commander logic (mostly consistent).

### Active
- Continuing per-file review of remaining head files: rest of `tests/test_common_terminal_driver.py`, `tests/test_common_admin_credentials.py`, `tests/test_common_recovery.py`, `tests/test_common_scope_errors.py`, `tests/test_common_stack_boundaries.py`, rest of `fos_commander.py`/`fos_cli_driver.py`/`terminal.py`/`cli_commands.py`/`launch.py`/`common.py`, `features/pki.py` (comment-only change), both READMEs.
- Evaluating the noted concerns list (duplicate-consumption of timeout Data by feature `on_output` implementations — need grep of `on_output`/`discard` across `fortinet/common/features/`; `None` replay-target edge; id-keyed retries; context-loss-before-validation ordering).
- Must still check whether any feature relies on old timeout-Data semantics (only-new-bytes) and whether retained-buffer exposure breaks them.

### Blocked
- (none)

## Next Move
1. Grep `fortinet/common/features/` head tree for `def on_output` and `discard(` usage to verify timeout-Data consumers (e.g. capture_config, license, image_info features) handle the new full-buffer semantics without duplicate processing.
2. Read remaining head test files (`test_common_admin_credentials.py`, `test_common_recovery.py`, `test_common_scope_errors.py`, rest of `test_common_stack_parsing.py`/`test_common_stack_boundaries.py`/`test_common_terminal_driver.py`) and `launch.py`, then skim both README diffs; finalize review findings and emit the trusted result schema, disclosing no-test-execution and manifest-incomplete coverage.

## Relevant Files
- `/source/manifest.json`: changed-path inventory; snapshot incompleteness details.
- `/source/diff.txt`: full PR diff (read with offsets; large).
- `/source/head/fortinet/common/cli_commands.py`: ContextLossAction, CommandSpec.context_loss/continuation, closes_scope, CommandAttempt.on_output, _flatten_quoted_lines.
- `/source/head/fortinet/common/fos_commander.py`: core scheduler — _complete_inflight ordering, _handle_context_loss, _restart_active_block, _restore_replay_context, _recovery_retries/_cleanup_retries, _handle_session_loss, on_state top-of-function CMD_PROMPT reset.
- `/source/head/fortinet/common/terminal.py`: Data/expect full-buffer timeout semantics, received_new_data, TRACE_LEVEL log change, buffer limit env.
- `/source/head/fortinet/common/fos_cli_driver.py`: stall detection, KernelPanicError, credential recovery state machine.
- `/source/head/fortinet/common/env.py`: FTNT_*/FOS_* alias precedence (unchanged but load-bearing for tests).
- `/source/head/fortinet/common/features/credentials.py`, `features/base.py`, `features/startup_config.py`, `features/pki.py`: feature lifecycle, DNS filtering, PKI comment change.
- `/source/head/fortinet/common/launch.py`: KernelPanicError catch → stop + raise; to be read.
- `/source/head/fortinet/tests/test_common_*.py`: new/changed tests defining expected behaviors (RecordingFeature, SerialConnection, make_stack helpers in test_common_stack_parsing.py).
- `/source/head/fortinet/fortigate/README.md`, `/source/head/fortinet/fortigate/docker/README.md`: docs to review (not yet read).
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d3cdf0001FqYFiAnsF2Q18P",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d399d0001Ds1IgkQWIg8sZ9",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 26862,
    "input": 25136,
    "output": 1714,
    "reasoning": 12,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d399d0001Ds1IgkQWIg8sZ9",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716361680,
    "completed": 1793716375026
  },
  "parentID": "msg_1a1d399bf001jpJwVa41DjfRYi",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 26862,
    "input": 25136,
    "output": 1714,
    "reasoning": 12,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 12
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716375027
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 13
step-start
{
  "type": "step-start",
  "id": "prt_1a1d3d2cf001CX98F2CWyjpqs7",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3cdf8001xPjYsI2LzMUvLt"
}
Reasoning
I need to continue from the handoff. Next steps: grep for on_output/discard in features, read remaining test files, launch.py, READMEs. Let me do batched tool calls.

Let me start with greps and reads in parallel.
I'll continue the review from where we left off: verify how feature `on_output` consumers handle the new timeout-`Data` semantics, read the remaining test files, `launch.py`, and the READMEs.
grep · completed

Input

{
  "pattern": "def on_output|discard\\(|expect\\(",
  "path": "/source/head/fortinet/common/features",
  "include": "*.py"
}

Output

Found 2 matches
/source/head/fortinet/common/features/base.py:
  Line 46:     def on_output(self, output):


/source/head/fortinet/common/features/license.py:
  Line 97:     def on_output(self, output):
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3d561001tbQe3TExrEEpqc",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3cdf8001xPjYsI2LzMUvLt",
  "callID": "call_fd48909782074f2a91a7aa9f",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "def on_output|discard\\(|expect\\(",
      "path": "/source/head/fortinet/common/features",
      "include": "*.py"
    },
    "output": "Found 2 matches\n/source/head/fortinet/common/features/base.py:\n  Line 46:     def on_output(self, output):\n\n\n/source/head/fortinet/common/features/license.py:\n  Line 97:     def on_output(self, output):\n",
    "title": "def on_output|discard\\(|expect\\(",
    "metadata": {
      "matches": 2,
      "truncated": false
    },
    "time": {
      "start": 1793716376934,
      "end": 1793716376946
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/launch.py"
}

Output

<path>/source/head/fortinet/common/launch.py</path>
<type>file</type>
<content>
1: #!/usr/bin/env python3
2: import argparse
3: import logging
4: import os
5: import re
6: import select
7: import signal
8: import sys
9: import time
10: from contextlib import contextmanager
11: 
12: import vrnetlab
13: from .common import Credentials, DEFAULT_PASSWORD, DEFAULT_USERNAME, DEF_POLICY_COMPLIANT_PASSWORD, TRACE_LEVEL
14: from .features import (
15:     CredentialsFeature,
16:     ConfigureMgmtDns,
17:     ConfigSaveFeature,
18:     FormatDisks,
19:     FeatureFileWatcher,
20:     DefaultConfig,
21:     ConfigureFortiGuardHooks,
22:     ReapplyFortiGuardHooks,
23:     SetLicense,
24:     WaitForLicenseValidation,
25:     WaitForFortiTokens,
26:     ConfigureMgmtNetwork,
27:     ReconfigureMgmtNetwork,
28:     MoveMgmtToVrf1,
29:     ImageInfo,
30:     InstallPkiCertificates,
31:     ApplyStartupConfig,
32:     ValidateProduct,
33: )
34: from .env import get_env
35: from .fos_cli_driver import FOSCliDriver, KernelPanicError
36: from .fos_commander import FOSCommander
37: from .host_forwarded_bridge import HostForwardedBridge
38: from .net_mgmt_strategy import NetMgmtStrategy
39: from .passthrough_redirect import PassthroughRedirect
40: from .terminal import Terminal
41: from .tftp import TFTPServer
42: 
43: 
44: def handle_SIGCHLD(_unused_signal, _unused_frame):
45:     os.waitpid(-1, os.WNOHANG)
46: 
47: 
48: def handle_SIGTERM(_unused_signal, _unused_frame):
49:     sys.exit(0)
50: 
51: 
52: signal.signal(signal.SIGINT, handle_SIGTERM)
53: signal.signal(signal.SIGTERM, handle_SIGTERM)
54: signal.signal(signal.SIGCHLD, handle_SIGCHLD)
55: 
56: TRACE_LEVEL_NUM = TRACE_LEVEL
57: # Appended to once per main-loop iteration; fos_healthcheck.py watches this
58: # file to tell a slow bootstrap from a wedged launcher. Keep in sync with the
59: # HEARTBEAT_FILE default in fos_healthcheck.py.
60: HEARTBEAT_FILE = get_env("FOS_HEARTBEAT_FILE", "/healthbeat")
61: logging.addLevelName(TRACE_LEVEL_NUM, "\x1b[1;35m\tTRACE\x1b[0m")
62: LOG_LEVEL_NAMES = {
63:     "TRACE": TRACE_LEVEL_NUM,
64:     "DEBUG": logging.DEBUG,
65:     "INFO": logging.INFO,
66:     "WARN": logging.WARN,
67:     "WARNING": logging.WARNING,
68:     "ERROR": logging.ERROR,
69:     "CRITICAL": logging.CRITICAL,
70:     "FATAL": logging.FATAL,
71: }
72: 
73: 
74: def trace(self, message, *args, **kws):
75:     # Yes, logger takes its '*args' as 'args'.
76:     if self.isEnabledFor(TRACE_LEVEL_NUM):
77:         self.log(TRACE_LEVEL_NUM, message, *args, **kws)
78: 
79: 
80: logging.Logger.trace = trace
81: MGMT_PASSTHROUGH_DEFAULT = True
82: TFTP_PORT = 69
83: TFTP_TID_RANGE = (52400, 52500)
84: TFTP_DIRECTORY = "/tftpboot"
85: 
86: 
87: def parse_log_level(value):
88:     if value is None or str(value).strip() == "":
89:         return logging.DEBUG
90:     value = str(value).strip()
91:     try:
92:         return int(value)
93:     except ValueError:
94:         pass
95:     normalized = value.upper()
96:     if normalized in LOG_LEVEL_NAMES:
97:         return LOG_LEVEL_NAMES[normalized]
98:     raise ValueError(
99:         "Invalid FOS_LOG_LEVEL. Use TRACE, DEBUG, INFO, WARN, ERROR, "
100:         "another Python logging level name, or a numeric level."
101:     )
102: 
103: 
104: def exit_on_bootstrap_error(value=None):
105:     """Return whether a bootstrap exception should terminate the VM.
106: 
107:     Bootstrap failures are fatal by default.  The opt-out is intentionally
108:     narrow: only the explicit value ``false`` disables termination, so a
109:     misspelled or otherwise invalid value keeps the fail-fast behavior.
110:     """
111:     if value is None:
112:         value = get_env("FOS_EXIT_ON_BOOTSTRAP_ERROR", "true")
113:     return str(value).strip().lower() != "false"
114: 
115: 
116: def container_dns_servers(path="/etc/resolv.conf"):
117:     """Return nameserver addresses configured for this container, in order."""
118:     try:
119:         with open(path, encoding="utf-8") as resolver_config:
120:             servers = []
121:             for line in resolver_config:
122:                 fields = line.split()
123:                 if len(fields) >= 2 and fields[0] == "nameserver":
124:                     servers.append(fields[1])
125:             return servers
126:     except OSError:
127:         return []
128: 
129: 
130: def apply_debug_feature_cutoff(features, stop_feature, logger):
131:     """Limit bootstrap features to those up to and including ``stop_feature``."""
132:     if stop_feature is None or str(stop_feature).strip() == "":
133:         return features
134: 
135:     stop_feature = str(stop_feature).strip()
136:     for index, feature in enumerate(features):
137:         if feature.name == stop_feature:
138:             selected = features[:index + 1]
139:             skipped = features[index + 1:]
140:             logger.warning(
141:                 "FOS_DEBUG_FEATURE=%s; stopping after feature %s. Skipping: %s",
142:                 stop_feature,
143:                 stop_feature,
144:                 ", ".join(feature.name for feature in skipped) or "(none)",
145:             )
146:             return selected
147: 
148:     available = ", ".join(feature.name for feature in features)
149:     raise ValueError(f"Unknown FOS_DEBUG_FEATURE '{stop_feature}'. Available features: {available}")
150: 
151: 
152: class FortiOSConsole(vrnetlab._Console):
153:     def __init__(self, driver):
154:         super().__init__(driver)
155:         self._output_enabled = True
156: 
157:     def _read(self):
158:         data = self._driver.channel.read()
159:         if data and self._output_enabled:
160:             sys.stdout.buffer.write(data)
161:             sys.stdout.buffer.flush()
162:         return data
163: 
164:     def read_very_eager(self):
165:         transport_socket = getattr(self._driver.transport, "socket", None)
166:         socket = getattr(transport_socket, "sock", None)
167:         if socket is not None:
168:             readable, _, _ = select.select([socket], [], [], 0)
169:             if not readable:
170:                 return b""
171:         return self._read()
172: 
173:     def read_blocking(self):
174:         return self._read()
175: 
176:     @contextmanager
177:     def suppress_output(self):
178:         output_enabled = self._output_enabled
179:         self._output_enabled = False
180:         try:
181:             yield
182:         finally:
183:             self._output_enabled = output_enabled
184: 
185: 
186: class FortiOS_vm(vrnetlab.VM):
187:     def __init__(self, hostname: str, username, password, conn_mode, mgmt_net: NetMgmtStrategy,
188:                  expected_product="FortiGate"):
189:         disk_image = None
190:         for e in os.listdir("."):
191:             if re.search(".qcow2$", e):
192:                 disk_image = "./" + e
193:         if disk_image is None:
194:             raise RuntimeError("Could not find image to boot")
195:         super(FortiOS_vm, self).__init__(
196:             username,
197:             password,
198:             disk_image=disk_image,
199:             ram=2048,
200:             driveif="virtio",
201:             # fortios fails to respond to network requests if the pci bus is setup :D
202:             provision_pci_bus=False,
203:             mgmt_passthrough=mgmt_net.mgmt_passthrough
204:         )
205:         self.tn = FortiOSConsole(self.scrapli_tn)
206: 
207:         self.logger.info(f"Launching. commandline: {' '.join(sys.argv)}")
208:         self.logger.warning("deploy --reconfigure, deploy --restore, redeploy, restart, restore, save, stop-then-start,"
209:                             " not supported at this moment.")
210:         self.conn_mode = conn_mode
211:         self.hostname = hostname
212:         self.num_nics = 12
213:         self.nic_type = "virtio-net-pci"
214:         self.highest_port = 0
215:         self.spins = 0
216:         self.stopped = False
217:         self._bootstrap_error = None
218:         self._exit_on_bootstrap_error = exit_on_bootstrap_error()
219:         self.waiting_for = False
220:         self._mgmt_net = mgmt_net
221:         self.expected_product = expected_product
222:         self._mgmt_net.configure_vm_mgmt(self)
223:         container_dns = container_dns_servers()
224:         primary_dns = get_env(
225:             "FOS_MGMT_DNS_PRIMARY",
226:             aliases=("FTNT_DNS_PRIMARY",),
227:         )
228:         secondary_dns = get_env(
229:             "FOS_MGMT_DNS_SECONDARY",
230:             aliases=("FTNT_DNS_SECONDARY",),
231:             legacy_aliases=("FTNT_MGMG_DNS_SECONDARY", "FOS_MGMG_DNS_SECONDARY"),
232:         )
233:         if primary_dns is None:
234:             primary_dns = container_dns[0] if container_dns else "1.1.1.1"
235:         if secondary_dns is None:
236:             secondary_dns = container_dns[1] if len(container_dns) > 1 else "8.8.8.8"
237:         self.mgmt_dns_primary = primary_dns
238:         self.mgmt_dns_secondary = secondary_dns
239:         self.mgmt_dns_protocol = get_env("FTNT_DNS_PROTOCOL", "cleartext")
240:         self.terminal = Terminal(self.tn, self.logger, default_wait=self.wait_pattern)
241:         desired_password = DEFAULT_PASSWORD if password is None else password
242:         self._bootstrap_username = DEFAULT_USERNAME
243:         self._bootstrap_password = DEF_POLICY_COMPLIANT_PASSWORD
244:         self.credentials = Credentials(self._bootstrap_username, self._bootstrap_password)
245:         self.desired_credentials = Credentials(username or DEFAULT_USERNAME, desired_password)
246:         self.commander = FOSCommander(
247:             terminal=self.terminal,
248:             logger=self.logger,
249:             continue_on_error=not self._exit_on_bootstrap_error,
250:         )
251:         self.fos_version = None
252:         self.fos_product = None
253:         self.driver = FOSCliDriver(
254:             self.terminal,
255:             self.commander,
256:             self.credentials,
257:             self.logger,
258:             self._bootstrap_password,
259:             self.activate_blank_credentials,
260:             self.activate_bootstrap_credentials,
261:             # Always retry the last accepted credentials after a desired
262:             # password transition is rejected. The bootstrap error policy
263:             # controls feature failures, not whether the console can recover.
264:             allow_credential_recovery=True,
265:         )
266:         configure_dns = ConfigureMgmtDns(self, self.commander)
267:         license_validation = WaitForLicenseValidation(self, self.commander)
268:         self._features = [
269:             ImageInfo(self, self.commander),
270:             ValidateProduct(self, self.commander, expected_product),
271:             FormatDisks(self, self.commander),
272:             CredentialsFeature(self, self.commander),
273:             ConfigureMgmtNetwork(self, self.commander),
274:             configure_dns,
275:             ConfigureFortiGuardHooks(self, self.commander),
276:             SetLicense(self, self.commander),
277:             ReapplyFortiGuardHooks(self, self.commander),
278:             DefaultConfig(self, self.commander),
279:             ReconfigureMgmtNetwork(self, self.commander),
280:             license_validation,
281:             WaitForFortiTokens(self, self.commander, license_validation),
282:             InstallPkiCertificates(self, self.commander),
283:             MoveMgmtToVrf1(self, self.commander),
284:             ConfigSaveFeature(self, self.commander),
285:             ApplyStartupConfig(self, self.commander),
286:         ]
287:         self._features = apply_debug_feature_cutoff(
288:             self._features,
289:             get_env("FOS_DEBUG_FEATURE"),
290:             self.logger,
291:         )
292:         self._file_watcher = FeatureFileWatcher(self._features, self.logger)
293:         self.commander.start(self._features)
294:         vrnetlab.run_command(
295:             ["qemu-img", "create", "-f", "qcow2", "empty.qcow2", "30G"]
296:         )
297: 
298:         # Comma-separated list of disk sizes to install in the machine. as accepted by qemu-img create.
299:         disk_specs = get_env("FOS_DISK_SPECS", "").split(",")
300:         if disk_specs[0] == '':
301:             self.logger.warning(
302:                 "No additional disks configured. Use FOS_DISK_SPECS to specify a comma-separated list of disk sizes")
303:             return
304:         index = 0
305:         for spec in disk_specs:
306:             index += 1
307:             # set up the extra empty disk image
308:             # for fortigate logs
309:             vrnetlab.run_command(
310:                 ["qemu-img", "create", "-f", "qcow2", f"empty{index}.qcow2", spec]
311:             )
312: 
313:             self.qemu_args.extend(
314:                 [
315:                     "-drive",
316:                     f"if=virtio,format=qcow2,file=empty{index}.qcow2,index={index}",
317:                 ]
318:             )
319: 
320:             index += 1
321: 
322:     def bootstrap_spin(self):
323:         """This function should be called periodically to do work.
324: 
325:         returns False when it has failed and given up, otherwise True
326:         """
327:         if self._bootstrap_error is not None:
328:             return False
329:         try:
330:             self.driver.process_state()
331:         except KernelPanicError:
332:             self.stop()
333:             raise
334:         except Exception as error:
335:             if self._exit_on_bootstrap_error or self.commander.startup_complete:
336:                 self.stop()
337:                 raise
338:             failed_work = self.commander.continue_after_error(
339:                 error,
340:                 at_command_prompt=self.driver.at_command_prompt,
341:             )
342:             if failed_work is not None:
343:                 self.logger.exception(
344:                     "Bootstrap work %s failed; continuing with remaining features "
345:                     "because FOS_EXIT_ON_BOOTSTRAP_ERROR=false",
346:                     failed_work,
347:                 )
348:                 return True
349:             self._bootstrap_error = error
350:             self.logger.exception(
351:                 "Bootstrap cannot continue safely; keeping the VM running for manual "
352:                 "repair because FOS_EXIT_ON_BOOTSTRAP_ERROR=false"
353:             )
354:             try:
355:                 self.terminal.close()
356:                 self.logger.info(
357:                     "Released the launcher's serial Telnet connection after bootstrap stopped"
358:                 )
359:             except Exception:
360:                 self.logger.exception(
361:                     "Failed to release the serial Telnet connection after bootstrap stopped"
362:                 )
363:             return False
364:         if self.driver.ready and not self.commander.feature_errors:
365:             self.running = True
366:         return True
367: 
368:     def work(self):
369:         self._write_heartbeat()
370:         super().work()
371:         if self.running:
372:             self._file_watcher.poll()
373:             if not self.driver.ready:
374:                 self.bootstrap_spin()
375: 
376:     def _write_heartbeat(self):
377:         """Append one byte to the healthcheck heartbeat file.
378: 
379:         ``fos_healthcheck.py`` blocks in "starting" as long as this file
380:         keeps growing, so a slow but progressing bootstrap never trips the
381:         Docker unhealthy threshold. A wedged launcher stops beating and the
382:         probe reports failure. Best-effort: a heartbeat write must never
383:         take down the main loop.
384:         """
385:         try:
386:             with open(HEARTBEAT_FILE, "a") as heartbeat_handle:
387:                 heartbeat_handle.write("\n")
388:         except OSError:
389:             self.logger.debug("Failed to write healthcheck heartbeat", exc_info=True)
390: 
391:     def connect_serial_console(self):
392:         try:
393:             self.terminal.close()
394:         except Exception:
395:             pass
396: 
397:         for attempt in range(1, vrnetlab.MAX_RETRIES + 1):
398:             try:
399:                 self.tn.open()
400:                 break
401:             except Exception:
402:                 if attempt == vrnetlab.MAX_RETRIES:
403:                     self.logger.exception("Failed to connect to VM serial port.")
404:                     self.stop()
405:                     raise
406:                 self.logger.error(
407:                     f"Unable to connect to VM serial port {5000 + self.num}, "
408:                     f"retrying in a second (attempt {attempt})"
409:                 )
410:                 time.sleep(1)
411: 
412:         self.stopped = False
413:         self.terminal.write(b"\r")
414: 
415:     def activate_desired_credentials(self):
416:         self.driver.remember_current_credentials()
417:         self.credentials.username = self.desired_credentials.username
418:         self.credentials.password = self.desired_credentials.password
419: 
420:     def activate_bootstrap_credentials(self):
421:         self.credentials.username = self._bootstrap_username
422:         self.credentials.password = self._bootstrap_password
423: 
424:     def activate_blank_credentials(self):
425:         self.credentials.password = ""
426: 
427:     def gen_mgmt(self):
428:         return self._mgmt_net.gen_mgmt(self)
429: 
430:     @staticmethod
431:     def mgmt_gateway_destination(gateway, mgmt_address):
432:         _address, separator, prefix = str(mgmt_address).partition("/")
433:         if separator and prefix:
434:             return f"{gateway}/{prefix}"
435:         return f"{gateway}/{'128' if ':' in str(gateway) else '32'}"
436: 
437:     def stop(self):
438:         self.stopped = True
439:         super().stop()
440: 
441: 
442: class FortiOS(vrnetlab.VR):
443:     def __init__(self, hostname, username, password, conn_mode, mgmt_net: NetMgmtStrategy,
444:                  expected_product="FortiGate"):
445:         super(FortiOS, self).__init__(username, password, mgmt_passthrough=mgmt_net.mgmt_passthrough)
446:         self.logger.debug("Hostname")
447:         self.logger.debug(hostname)
448:         self.vms = [FortiOS_vm(hostname, username, password, conn_mode, mgmt_net=mgmt_net,
449:                                expected_product=expected_product)]
450: 
451: 
452: def main(expected_product="FortiGate"):
453: 
454:     parser = argparse.ArgumentParser(description="")
455:     parser.add_argument(
456:         "--trace", action="store_true", help="enable trace level logging"
457:     )
458:     parser.add_argument("--hostname", default="vr-fortinet", help="Fortinet hostname")
459:     parser.add_argument("--username", default=None, help="Username")
460:     parser.add_argument("--password", default=None, help="Password", nargs="?")
461:     parser.add_argument(
462:         "--connection-mode",
463:         default="tc",
464:         help="Connection mode to use in the datapath",
465:     )
466:     args = parser.parse_args()
467: 
468:     LOG_FORMAT = "%(asctime)s: %(module)-10s %(levelname)-8s %(message)s"
469:     logging.basicConfig(format=LOG_FORMAT)
470:     logger = logging.getLogger()
471: 
472:     logger.setLevel(parse_log_level(get_env("FOS_LOG_LEVEL")))
473: 
474:     mgmt_passthrough = (
475:         os.environ.get("CLAB_MGMT_PASSTHROUGH", "").lower() == "true"
476:         if os.environ.get("CLAB_MGMT_PASSTHROUGH")
477:         else MGMT_PASSTHROUGH_DEFAULT
478:     )
479: 
480:     tftp_server = None
481:     mgmt_net = None
482:     if mgmt_passthrough:
483:         mgmt_net = PassthroughRedirect([f"udp:{TFTP_PORT}", f"udp:{'-'.join(map(str, TFTP_TID_RANGE))}"])
484:         mgmt_net.prep()
485:         tftp_server = TFTPServer(mgmt_net=mgmt_net,
486:                                  srv_port=TFTP_PORT,
487:                                  tid_range=TFTP_TID_RANGE,
488:                                  directory=TFTP_DIRECTORY)
489:     else:
490:         mgmt_net = HostForwardedBridge()
491:         mgmt_net.prep()
492:         tftp_server = TFTPServer(srv_port=TFTP_PORT,
493:                                  mgmt_net=mgmt_net,
494:                                  directory=TFTP_DIRECTORY)
495: 
496:     vr = FortiOS(
497:         args.hostname, args.username, args.password, conn_mode=args.connection_mode,
498:         mgmt_net=mgmt_net, expected_product=expected_product
499:     )
500:     tftp_server.launch()
501:     vrnetlab.boot_delay()
502:     vr.start()
503: 
504: 
505: if __name__ == "__main__":
506:     main(get_env("FOS_EXPECTED_PRODUCT", "FortiGate"))

(End of file - total 506 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3d5a6001U00OzbPBTzPjbF",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3cdf8001xPjYsI2LzMUvLt",
  "callID": "call_d64d8683bbe24f5c993be17a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/launch.py"
    },
    "output": "<path>/source/head/fortinet/common/launch.py</path>\n<type>file</type>\n<content>\n1: #!/usr/bin/env python3\n2: import argparse\n3: import logging\n4: import os\n5: import re\n6: import select\n7: import signal\n8: import sys\n9: import time\n10: from contextlib import contextmanager\n11: \n12: import vrnetlab\n13: from .common import Credentials, DEFAULT_PASSWORD, DEFAULT_USERNAME, DEF_POLICY_COMPLIANT_PASSWORD, TRACE_LEVEL\n14: from .features import (\n15:     CredentialsFeature,\n16:     ConfigureMgmtDns,\n17:     ConfigSaveFeature,\n18:     FormatDisks,\n19:     FeatureFileWatcher,\n20:     DefaultConfig,\n21:     ConfigureFortiGuardHooks,\n22:     ReapplyFortiGuardHooks,\n23:     SetLicense,\n24:     WaitForLicenseValidation,\n25:     WaitForFortiTokens,\n26:     ConfigureMgmtNetwork,\n27:     ReconfigureMgmtNetwork,\n28:     MoveMgmtToVrf1,\n29:     ImageInfo,\n30:     InstallPkiCertificates,\n31:     ApplyStartupConfig,\n32:     ValidateProduct,\n33: )\n34: from .env import get_env\n35: from .fos_cli_driver import FOSCliDriver, KernelPanicError\n36: from .fos_commander import FOSCommander\n37: from .host_forwarded_bridge import HostForwardedBridge\n38: from .net_mgmt_strategy import NetMgmtStrategy\n39: from .passthrough_redirect import PassthroughRedirect\n40: from .terminal import Terminal\n41: from .tftp import TFTPServer\n42: \n43: \n44: def handle_SIGCHLD(_unused_signal, _unused_frame):\n45:     os.waitpid(-1, os.WNOHANG)\n46: \n47: \n48: def handle_SIGTERM(_unused_signal, _unused_frame):\n49:     sys.exit(0)\n50: \n51: \n52: signal.signal(signal.SIGINT, handle_SIGTERM)\n53: signal.signal(signal.SIGTERM, handle_SIGTERM)\n54: signal.signal(signal.SIGCHLD, handle_SIGCHLD)\n55: \n56: TRACE_LEVEL_NUM = TRACE_LEVEL\n57: # Appended to once per main-loop iteration; fos_healthcheck.py watches this\n58: # file to tell a slow bootstrap from a wedged launcher. Keep in sync with the\n59: # HEARTBEAT_FILE default in fos_healthcheck.py.\n60: HEARTBEAT_FILE = get_env(\"FOS_HEARTBEAT_FILE\", \"/healthbeat\")\n61: logging.addLevelName(TRACE_LEVEL_NUM, \"\\x1b[1;35m\\tTRACE\\x1b[0m\")\n62: LOG_LEVEL_NAMES = {\n63:     \"TRACE\": TRACE_LEVEL_NUM,\n64:     \"DEBUG\": logging.DEBUG,\n65:     \"INFO\": logging.INFO,\n66:     \"WARN\": logging.WARN,\n67:     \"WARNING\": logging.WARNING,\n68:     \"ERROR\": logging.ERROR,\n69:     \"CRITICAL\": logging.CRITICAL,\n70:     \"FATAL\": logging.FATAL,\n71: }\n72: \n73: \n74: def trace(self, message, *args, **kws):\n75:     # Yes, logger takes its '*args' as 'args'.\n76:     if self.isEnabledFor(TRACE_LEVEL_NUM):\n77:         self.log(TRACE_LEVEL_NUM, message, *args, **kws)\n78: \n79: \n80: logging.Logger.trace = trace\n81: MGMT_PASSTHROUGH_DEFAULT = True\n82: TFTP_PORT = 69\n83: TFTP_TID_RANGE = (52400, 52500)\n84: TFTP_DIRECTORY = \"/tftpboot\"\n85: \n86: \n87: def parse_log_level(value):\n88:     if value is None or str(value).strip() == \"\":\n89:         return logging.DEBUG\n90:     value = str(value).strip()\n91:     try:\n92:         return int(value)\n93:     except ValueError:\n94:         pass\n95:     normalized = value.upper()\n96:     if normalized in LOG_LEVEL_NAMES:\n97:         return LOG_LEVEL_NAMES[normalized]\n98:     raise ValueError(\n99:         \"Invalid FOS_LOG_LEVEL. Use TRACE, DEBUG, INFO, WARN, ERROR, \"\n100:         \"another Python logging level name, or a numeric level.\"\n101:     )\n102: \n103: \n104: def exit_on_bootstrap_error(value=None):\n105:     \"\"\"Return whether a bootstrap exception should terminate the VM.\n106: \n107:     Bootstrap failures are fatal by default.  The opt-out is intentionally\n108:     narrow: only the explicit value ``false`` disables termination, so a\n109:     misspelled or otherwise invalid value keeps the fail-fast behavior.\n110:     \"\"\"\n111:     if value is None:\n112:         value = get_env(\"FOS_EXIT_ON_BOOTSTRAP_ERROR\", \"true\")\n113:     return str(value).strip().lower() != \"false\"\n114: \n115: \n116: def container_dns_servers(path=\"/etc/resolv.conf\"):\n117:     \"\"\"Return nameserver addresses configured for this container, in order.\"\"\"\n118:     try:\n119:         with open(path, encoding=\"utf-8\") as resolver_config:\n120:             servers = []\n121:             for line in resolver_config:\n122:                 fields = line.split()\n123:                 if len(fields) >= 2 and fields[0] == \"nameserver\":\n124:                     servers.append(fields[1])\n125:             return servers\n126:     except OSError:\n127:         return []\n128: \n129: \n130: def apply_debug_feature_cutoff(features, stop_feature, logger):\n131:     \"\"\"Limit bootstrap features to those up to and including ``stop_feature``.\"\"\"\n132:     if stop_feature is None or str(stop_feature).strip() == \"\":\n133:         return features\n134: \n135:     stop_feature = str(stop_feature).strip()\n136:     for index, feature in enumerate(features):\n137:         if feature.name == stop_feature:\n138:             selected = features[:index + 1]\n139:             skipped = features[index + 1:]\n140:             logger.warning(\n141:                 \"FOS_DEBUG_FEATURE=%s; stopping after feature %s. Skipping: %s\",\n142:                 stop_feature,\n143:                 stop_feature,\n144:                 \", \".join(feature.name for feature in skipped) or \"(none)\",\n145:             )\n146:             return selected\n147: \n148:     available = \", \".join(feature.name for feature in features)\n149:     raise ValueError(f\"Unknown FOS_DEBUG_FEATURE '{stop_feature}'. Available features: {available}\")\n150: \n151: \n152: class FortiOSConsole(vrnetlab._Console):\n153:     def __init__(self, driver):\n154:         super().__init__(driver)\n155:         self._output_enabled = True\n156: \n157:     def _read(self):\n158:         data = self._driver.channel.read()\n159:         if data and self._output_enabled:\n160:             sys.stdout.buffer.write(data)\n161:             sys.stdout.buffer.flush()\n162:         return data\n163: \n164:     def read_very_eager(self):\n165:         transport_socket = getattr(self._driver.transport, \"socket\", None)\n166:         socket = getattr(transport_socket, \"sock\", None)\n167:         if socket is not None:\n168:             readable, _, _ = select.select([socket], [], [], 0)\n169:             if not readable:\n170:                 return b\"\"\n171:         return self._read()\n172: \n173:     def read_blocking(self):\n174:         return self._read()\n175: \n176:     @contextmanager\n177:     def suppress_output(self):\n178:         output_enabled = self._output_enabled\n179:         self._output_enabled = False\n180:         try:\n181:             yield\n182:         finally:\n183:             self._output_enabled = output_enabled\n184: \n185: \n186: class FortiOS_vm(vrnetlab.VM):\n187:     def __init__(self, hostname: str, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n188:                  expected_product=\"FortiGate\"):\n189:         disk_image = None\n190:         for e in os.listdir(\".\"):\n191:             if re.search(\".qcow2$\", e):\n192:                 disk_image = \"./\" + e\n193:         if disk_image is None:\n194:             raise RuntimeError(\"Could not find image to boot\")\n195:         super(FortiOS_vm, self).__init__(\n196:             username,\n197:             password,\n198:             disk_image=disk_image,\n199:             ram=2048,\n200:             driveif=\"virtio\",\n201:             # fortios fails to respond to network requests if the pci bus is setup :D\n202:             provision_pci_bus=False,\n203:             mgmt_passthrough=mgmt_net.mgmt_passthrough\n204:         )\n205:         self.tn = FortiOSConsole(self.scrapli_tn)\n206: \n207:         self.logger.info(f\"Launching. commandline: {' '.join(sys.argv)}\")\n208:         self.logger.warning(\"deploy --reconfigure, deploy --restore, redeploy, restart, restore, save, stop-then-start,\"\n209:                             \" not supported at this moment.\")\n210:         self.conn_mode = conn_mode\n211:         self.hostname = hostname\n212:         self.num_nics = 12\n213:         self.nic_type = \"virtio-net-pci\"\n214:         self.highest_port = 0\n215:         self.spins = 0\n216:         self.stopped = False\n217:         self._bootstrap_error = None\n218:         self._exit_on_bootstrap_error = exit_on_bootstrap_error()\n219:         self.waiting_for = False\n220:         self._mgmt_net = mgmt_net\n221:         self.expected_product = expected_product\n222:         self._mgmt_net.configure_vm_mgmt(self)\n223:         container_dns = container_dns_servers()\n224:         primary_dns = get_env(\n225:             \"FOS_MGMT_DNS_PRIMARY\",\n226:             aliases=(\"FTNT_DNS_PRIMARY\",),\n227:         )\n228:         secondary_dns = get_env(\n229:             \"FOS_MGMT_DNS_SECONDARY\",\n230:             aliases=(\"FTNT_DNS_SECONDARY\",),\n231:             legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n232:         )\n233:         if primary_dns is None:\n234:             primary_dns = container_dns[0] if container_dns else \"1.1.1.1\"\n235:         if secondary_dns is None:\n236:             secondary_dns = container_dns[1] if len(container_dns) > 1 else \"8.8.8.8\"\n237:         self.mgmt_dns_primary = primary_dns\n238:         self.mgmt_dns_secondary = secondary_dns\n239:         self.mgmt_dns_protocol = get_env(\"FTNT_DNS_PROTOCOL\", \"cleartext\")\n240:         self.terminal = Terminal(self.tn, self.logger, default_wait=self.wait_pattern)\n241:         desired_password = DEFAULT_PASSWORD if password is None else password\n242:         self._bootstrap_username = DEFAULT_USERNAME\n243:         self._bootstrap_password = DEF_POLICY_COMPLIANT_PASSWORD\n244:         self.credentials = Credentials(self._bootstrap_username, self._bootstrap_password)\n245:         self.desired_credentials = Credentials(username or DEFAULT_USERNAME, desired_password)\n246:         self.commander = FOSCommander(\n247:             terminal=self.terminal,\n248:             logger=self.logger,\n249:             continue_on_error=not self._exit_on_bootstrap_error,\n250:         )\n251:         self.fos_version = None\n252:         self.fos_product = None\n253:         self.driver = FOSCliDriver(\n254:             self.terminal,\n255:             self.commander,\n256:             self.credentials,\n257:             self.logger,\n258:             self._bootstrap_password,\n259:             self.activate_blank_credentials,\n260:             self.activate_bootstrap_credentials,\n261:             # Always retry the last accepted credentials after a desired\n262:             # password transition is rejected. The bootstrap error policy\n263:             # controls feature failures, not whether the console can recover.\n264:             allow_credential_recovery=True,\n265:         )\n266:         configure_dns = ConfigureMgmtDns(self, self.commander)\n267:         license_validation = WaitForLicenseValidation(self, self.commander)\n268:         self._features = [\n269:             ImageInfo(self, self.commander),\n270:             ValidateProduct(self, self.commander, expected_product),\n271:             FormatDisks(self, self.commander),\n272:             CredentialsFeature(self, self.commander),\n273:             ConfigureMgmtNetwork(self, self.commander),\n274:             configure_dns,\n275:             ConfigureFortiGuardHooks(self, self.commander),\n276:             SetLicense(self, self.commander),\n277:             ReapplyFortiGuardHooks(self, self.commander),\n278:             DefaultConfig(self, self.commander),\n279:             ReconfigureMgmtNetwork(self, self.commander),\n280:             license_validation,\n281:             WaitForFortiTokens(self, self.commander, license_validation),\n282:             InstallPkiCertificates(self, self.commander),\n283:             MoveMgmtToVrf1(self, self.commander),\n284:             ConfigSaveFeature(self, self.commander),\n285:             ApplyStartupConfig(self, self.commander),\n286:         ]\n287:         self._features = apply_debug_feature_cutoff(\n288:             self._features,\n289:             get_env(\"FOS_DEBUG_FEATURE\"),\n290:             self.logger,\n291:         )\n292:         self._file_watcher = FeatureFileWatcher(self._features, self.logger)\n293:         self.commander.start(self._features)\n294:         vrnetlab.run_command(\n295:             [\"qemu-img\", \"create\", \"-f\", \"qcow2\", \"empty.qcow2\", \"30G\"]\n296:         )\n297: \n298:         # Comma-separated list of disk sizes to install in the machine. as accepted by qemu-img create.\n299:         disk_specs = get_env(\"FOS_DISK_SPECS\", \"\").split(\",\")\n300:         if disk_specs[0] == '':\n301:             self.logger.warning(\n302:                 \"No additional disks configured. Use FOS_DISK_SPECS to specify a comma-separated list of disk sizes\")\n303:             return\n304:         index = 0\n305:         for spec in disk_specs:\n306:             index += 1\n307:             # set up the extra empty disk image\n308:             # for fortigate logs\n309:             vrnetlab.run_command(\n310:                 [\"qemu-img\", \"create\", \"-f\", \"qcow2\", f\"empty{index}.qcow2\", spec]\n311:             )\n312: \n313:             self.qemu_args.extend(\n314:                 [\n315:                     \"-drive\",\n316:                     f\"if=virtio,format=qcow2,file=empty{index}.qcow2,index={index}\",\n317:                 ]\n318:             )\n319: \n320:             index += 1\n321: \n322:     def bootstrap_spin(self):\n323:         \"\"\"This function should be called periodically to do work.\n324: \n325:         returns False when it has failed and given up, otherwise True\n326:         \"\"\"\n327:         if self._bootstrap_error is not None:\n328:             return False\n329:         try:\n330:             self.driver.process_state()\n331:         except KernelPanicError:\n332:             self.stop()\n333:             raise\n334:         except Exception as error:\n335:             if self._exit_on_bootstrap_error or self.commander.startup_complete:\n336:                 self.stop()\n337:                 raise\n338:             failed_work = self.commander.continue_after_error(\n339:                 error,\n340:                 at_command_prompt=self.driver.at_command_prompt,\n341:             )\n342:             if failed_work is not None:\n343:                 self.logger.exception(\n344:                     \"Bootstrap work %s failed; continuing with remaining features \"\n345:                     \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n346:                     failed_work,\n347:                 )\n348:                 return True\n349:             self._bootstrap_error = error\n350:             self.logger.exception(\n351:                 \"Bootstrap cannot continue safely; keeping the VM running for manual \"\n352:                 \"repair because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\"\n353:             )\n354:             try:\n355:                 self.terminal.close()\n356:                 self.logger.info(\n357:                     \"Released the launcher's serial Telnet connection after bootstrap stopped\"\n358:                 )\n359:             except Exception:\n360:                 self.logger.exception(\n361:                     \"Failed to release the serial Telnet connection after bootstrap stopped\"\n362:                 )\n363:             return False\n364:         if self.driver.ready and not self.commander.feature_errors:\n365:             self.running = True\n366:         return True\n367: \n368:     def work(self):\n369:         self._write_heartbeat()\n370:         super().work()\n371:         if self.running:\n372:             self._file_watcher.poll()\n373:             if not self.driver.ready:\n374:                 self.bootstrap_spin()\n375: \n376:     def _write_heartbeat(self):\n377:         \"\"\"Append one byte to the healthcheck heartbeat file.\n378: \n379:         ``fos_healthcheck.py`` blocks in \"starting\" as long as this file\n380:         keeps growing, so a slow but progressing bootstrap never trips the\n381:         Docker unhealthy threshold. A wedged launcher stops beating and the\n382:         probe reports failure. Best-effort: a heartbeat write must never\n383:         take down the main loop.\n384:         \"\"\"\n385:         try:\n386:             with open(HEARTBEAT_FILE, \"a\") as heartbeat_handle:\n387:                 heartbeat_handle.write(\"\\n\")\n388:         except OSError:\n389:             self.logger.debug(\"Failed to write healthcheck heartbeat\", exc_info=True)\n390: \n391:     def connect_serial_console(self):\n392:         try:\n393:             self.terminal.close()\n394:         except Exception:\n395:             pass\n396: \n397:         for attempt in range(1, vrnetlab.MAX_RETRIES + 1):\n398:             try:\n399:                 self.tn.open()\n400:                 break\n401:             except Exception:\n402:                 if attempt == vrnetlab.MAX_RETRIES:\n403:                     self.logger.exception(\"Failed to connect to VM serial port.\")\n404:                     self.stop()\n405:                     raise\n406:                 self.logger.error(\n407:                     f\"Unable to connect to VM serial port {5000 + self.num}, \"\n408:                     f\"retrying in a second (attempt {attempt})\"\n409:                 )\n410:                 time.sleep(1)\n411: \n412:         self.stopped = False\n413:         self.terminal.write(b\"\\r\")\n414: \n415:     def activate_desired_credentials(self):\n416:         self.driver.remember_current_credentials()\n417:         self.credentials.username = self.desired_credentials.username\n418:         self.credentials.password = self.desired_credentials.password\n419: \n420:     def activate_bootstrap_credentials(self):\n421:         self.credentials.username = self._bootstrap_username\n422:         self.credentials.password = self._bootstrap_password\n423: \n424:     def activate_blank_credentials(self):\n425:         self.credentials.password = \"\"\n426: \n427:     def gen_mgmt(self):\n428:         return self._mgmt_net.gen_mgmt(self)\n429: \n430:     @staticmethod\n431:     def mgmt_gateway_destination(gateway, mgmt_address):\n432:         _address, separator, prefix = str(mgmt_address).partition(\"/\")\n433:         if separator and prefix:\n434:             return f\"{gateway}/{prefix}\"\n435:         return f\"{gateway}/{'128' if ':' in str(gateway) else '32'}\"\n436: \n437:     def stop(self):\n438:         self.stopped = True\n439:         super().stop()\n440: \n441: \n442: class FortiOS(vrnetlab.VR):\n443:     def __init__(self, hostname, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n444:                  expected_product=\"FortiGate\"):\n445:         super(FortiOS, self).__init__(username, password, mgmt_passthrough=mgmt_net.mgmt_passthrough)\n446:         self.logger.debug(\"Hostname\")\n447:         self.logger.debug(hostname)\n448:         self.vms = [FortiOS_vm(hostname, username, password, conn_mode, mgmt_net=mgmt_net,\n449:                                expected_product=expected_product)]\n450: \n451: \n452: def main(expected_product=\"FortiGate\"):\n453: \n454:     parser = argparse.ArgumentParser(description=\"\")\n455:     parser.add_argument(\n456:         \"--trace\", action=\"store_true\", help=\"enable trace level logging\"\n457:     )\n458:     parser.add_argument(\"--hostname\", default=\"vr-fortinet\", help=\"Fortinet hostname\")\n459:     parser.add_argument(\"--username\", default=None, help=\"Username\")\n460:     parser.add_argument(\"--password\", default=None, help=\"Password\", nargs=\"?\")\n461:     parser.add_argument(\n462:         \"--connection-mode\",\n463:         default=\"tc\",\n464:         help=\"Connection mode to use in the datapath\",\n465:     )\n466:     args = parser.parse_args()\n467: \n468:     LOG_FORMAT = \"%(asctime)s: %(module)-10s %(levelname)-8s %(message)s\"\n469:     logging.basicConfig(format=LOG_FORMAT)\n470:     logger = logging.getLogger()\n471: \n472:     logger.setLevel(parse_log_level(get_env(\"FOS_LOG_LEVEL\")))\n473: \n474:     mgmt_passthrough = (\n475:         os.environ.get(\"CLAB_MGMT_PASSTHROUGH\", \"\").lower() == \"true\"\n476:         if os.environ.get(\"CLAB_MGMT_PASSTHROUGH\")\n477:         else MGMT_PASSTHROUGH_DEFAULT\n478:     )\n479: \n480:     tftp_server = None\n481:     mgmt_net = None\n482:     if mgmt_passthrough:\n483:         mgmt_net = PassthroughRedirect([f\"udp:{TFTP_PORT}\", f\"udp:{'-'.join(map(str, TFTP_TID_RANGE))}\"])\n484:         mgmt_net.prep()\n485:         tftp_server = TFTPServer(mgmt_net=mgmt_net,\n486:                                  srv_port=TFTP_PORT,\n487:                                  tid_range=TFTP_TID_RANGE,\n488:                                  directory=TFTP_DIRECTORY)\n489:     else:\n490:         mgmt_net = HostForwardedBridge()\n491:         mgmt_net.prep()\n492:         tftp_server = TFTPServer(srv_port=TFTP_PORT,\n493:                                  mgmt_net=mgmt_net,\n494:                                  directory=TFTP_DIRECTORY)\n495: \n496:     vr = FortiOS(\n497:         args.hostname, args.username, args.password, conn_mode=args.connection_mode,\n498:         mgmt_net=mgmt_net, expected_product=expected_product\n499:     )\n500:     tftp_server.launch()\n501:     vrnetlab.boot_delay()\n502:     vr.start()\n503: \n504: \n505: if __name__ == \"__main__\":\n506:     main(get_env(\"FOS_EXPECTED_PRODUCT\", \"FortiGate\"))\n\n(End of file - total 506 lines)\n</content>",
    "title": "source/head/fortinet/common/launch.py",
    "metadata": {
      "preview": "#!/usr/bin/env python3\nimport argparse\nimport logging\nimport os\nimport re\nimport select\nimport signal\nimport sys\nimport time\nfrom contextlib import contextmanager\n\nimport vrnetlab\nfrom .common import Credentials, DEFAULT_PASSWORD, DEFAULT_USERNAME, DEF_POLICY_COMPLIANT_PASSWORD, TRACE_LEVEL\nfrom .features import (\n    CredentialsFeature,\n    ConfigureMgmtDns,\n    ConfigSaveFeature,\n    FormatDisks,\n    FeatureFileWatcher,\n    DefaultConfig,",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/launch.py",
        "text": "#!/usr/bin/env python3\nimport argparse\nimport logging\nimport os\nimport re\nimport select\nimport signal\nimport sys\nimport time\nfrom contextlib import contextmanager\n\nimport vrnetlab\nfrom .common import Credentials, DEFAULT_PASSWORD, DEFAULT_USERNAME, DEF_POLICY_COMPLIANT_PASSWORD, TRACE_LEVEL\nfrom .features import (\n    CredentialsFeature,\n    ConfigureMgmtDns,\n    ConfigSaveFeature,\n    FormatDisks,\n    FeatureFileWatcher,\n    DefaultConfig,\n    ConfigureFortiGuardHooks,\n    ReapplyFortiGuardHooks,\n    SetLicense,\n    WaitForLicenseValidation,\n    WaitForFortiTokens,\n    ConfigureMgmtNetwork,\n    ReconfigureMgmtNetwork,\n    MoveMgmtToVrf1,\n    ImageInfo,\n    InstallPkiCertificates,\n    ApplyStartupConfig,\n    ValidateProduct,\n)\nfrom .env import get_env\nfrom .fos_cli_driver import FOSCliDriver, KernelPanicError\nfrom .fos_commander import FOSCommander\nfrom .host_forwarded_bridge import HostForwardedBridge\nfrom .net_mgmt_strategy import NetMgmtStrategy\nfrom .passthrough_redirect import PassthroughRedirect\nfrom .terminal import Terminal\nfrom .tftp import TFTPServer\n\n\ndef handle_SIGCHLD(_unused_signal, _unused_frame):\n    os.waitpid(-1, os.WNOHANG)\n\n\ndef handle_SIGTERM(_unused_signal, _unused_frame):\n    sys.exit(0)\n\n\nsignal.signal(signal.SIGINT, handle_SIGTERM)\nsignal.signal(signal.SIGTERM, handle_SIGTERM)\nsignal.signal(signal.SIGCHLD, handle_SIGCHLD)\n\nTRACE_LEVEL_NUM = TRACE_LEVEL\n# Appended to once per main-loop iteration; fos_healthcheck.py watches this\n# file to tell a slow bootstrap from a wedged launcher. Keep in sync with the\n# HEARTBEAT_FILE default in fos_healthcheck.py.\nHEARTBEAT_FILE = get_env(\"FOS_HEARTBEAT_FILE\", \"/healthbeat\")\nlogging.addLevelName(TRACE_LEVEL_NUM, \"\\x1b[1;35m\\tTRACE\\x1b[0m\")\nLOG_LEVEL_NAMES = {\n    \"TRACE\": TRACE_LEVEL_NUM,\n    \"DEBUG\": logging.DEBUG,\n    \"INFO\": logging.INFO,\n    \"WARN\": logging.WARN,\n    \"WARNING\": logging.WARNING,\n    \"ERROR\": logging.ERROR,\n    \"CRITICAL\": logging.CRITICAL,\n    \"FATAL\": logging.FATAL,\n}\n\n\ndef trace(self, message, *args, **kws):\n    # Yes, logger takes its '*args' as 'args'.\n    if self.isEnabledFor(TRACE_LEVEL_NUM):\n        self.log(TRACE_LEVEL_NUM, message, *args, **kws)\n\n\nlogging.Logger.trace = trace\nMGMT_PASSTHROUGH_DEFAULT = True\nTFTP_PORT = 69\nTFTP_TID_RANGE = (52400, 52500)\nTFTP_DIRECTORY = \"/tftpboot\"\n\n\ndef parse_log_level(value):\n    if value is None or str(value).strip() == \"\":\n        return logging.DEBUG\n    value = str(value).strip()\n    try:\n        return int(value)\n    except ValueError:\n        pass\n    normalized = value.upper()\n    if normalized in LOG_LEVEL_NAMES:\n        return LOG_LEVEL_NAMES[normalized]\n    raise ValueError(\n        \"Invalid FOS_LOG_LEVEL. Use TRACE, DEBUG, INFO, WARN, ERROR, \"\n        \"another Python logging level name, or a numeric level.\"\n    )\n\n\ndef exit_on_bootstrap_error(value=None):\n    \"\"\"Return whether a bootstrap exception should terminate the VM.\n\n    Bootstrap failures are fatal by default.  The opt-out is intentionally\n    narrow: only the explicit value ``false`` disables termination, so a\n    misspelled or otherwise invalid value keeps the fail-fast behavior.\n    \"\"\"\n    if value is None:\n        value = get_env(\"FOS_EXIT_ON_BOOTSTRAP_ERROR\", \"true\")\n    return str(value).strip().lower() != \"false\"\n\n\ndef container_dns_servers(path=\"/etc/resolv.conf\"):\n    \"\"\"Return nameserver addresses configured for this container, in order.\"\"\"\n    try:\n        with open(path, encoding=\"utf-8\") as resolver_config:\n            servers = []\n            for line in resolver_config:\n                fields = line.split()\n                if len(fields) >= 2 and fields[0] == \"nameserver\":\n                    servers.append(fields[1])\n            return servers\n    except OSError:\n        return []\n\n\ndef apply_debug_feature_cutoff(features, stop_feature, logger):\n    \"\"\"Limit bootstrap features to those up to and including ``stop_feature``.\"\"\"\n    if stop_feature is None or str(stop_feature).strip() == \"\":\n        return features\n\n    stop_feature = str(stop_feature).strip()\n    for index, feature in enumerate(features):\n        if feature.name == stop_feature:\n            selected = features[:index + 1]\n            skipped = features[index + 1:]\n            logger.warning(\n                \"FOS_DEBUG_FEATURE=%s; stopping after feature %s. Skipping: %s\",\n                stop_feature,\n                stop_feature,\n                \", \".join(feature.name for feature in skipped) or \"(none)\",\n            )\n            return selected\n\n    available = \", \".join(feature.name for feature in features)\n    raise ValueError(f\"Unknown FOS_DEBUG_FEATURE '{stop_feature}'. Available features: {available}\")\n\n\nclass FortiOSConsole(vrnetlab._Console):\n    def __init__(self, driver):\n        super().__init__(driver)\n        self._output_enabled = True\n\n    def _read(self):\n        data = self._driver.channel.read()\n        if data and self._output_enabled:\n            sys.stdout.buffer.write(data)\n            sys.stdout.buffer.flush()\n        return data\n\n    def read_very_eager(self):\n        transport_socket = getattr(self._driver.transport, \"socket\", None)\n        socket = getattr(transport_socket, \"sock\", None)\n        if socket is not None:\n            readable, _, _ = select.select([socket], [], [], 0)\n            if not readable:\n                return b\"\"\n        return self._read()\n\n    def read_blocking(self):\n        return self._read()\n\n    @contextmanager\n    def suppress_output(self):\n        output_enabled = self._output_enabled\n        self._output_enabled = False\n        try:\n            yield\n        finally:\n            self._output_enabled = output_enabled\n\n\nclass FortiOS_vm(vrnetlab.VM):\n    def __init__(self, hostname: str, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n                 expected_product=\"FortiGate\"):\n        disk_image = None\n        for e in os.listdir(\".\"):\n            if re.search(\".qcow2$\", e):\n                disk_image = \"./\" + e\n        if disk_image is None:\n            raise RuntimeError(\"Could not find image to boot\")\n        super(FortiOS_vm, self).__init__(\n            username,\n            password,\n            disk_image=disk_image,\n            ram=2048,\n            driveif=\"virtio\",\n            # fortios fails to respond to network requests if the pci bus is setup :D\n            provision_pci_bus=False,\n            mgmt_passthrough=mgmt_net.mgmt_passthrough\n        )\n        self.tn = FortiOSConsole(self.scrapli_tn)\n\n        self.logger.info(f\"Launching. commandline: {' '.join(sys.argv)}\")\n        self.logger.warning(\"deploy --reconfigure, deploy --restore, redeploy, restart, restore, save, stop-then-start,\"\n                            \" not supported at this moment.\")\n        self.conn_mode = conn_mode\n        self.hostname = hostname\n        self.num_nics = 12\n        self.nic_type = \"virtio-net-pci\"\n        self.highest_port = 0\n        self.spins = 0\n        self.stopped = False\n        self._bootstrap_error = None\n        self._exit_on_bootstrap_error = exit_on_bootstrap_error()\n        self.waiting_for = False\n        self._mgmt_net = mgmt_net\n        self.expected_product = expected_product\n        self._mgmt_net.configure_vm_mgmt(self)\n        container_dns = container_dns_servers()\n        primary_dns = get_env(\n            \"FOS_MGMT_DNS_PRIMARY\",\n            aliases=(\"FTNT_DNS_PRIMARY\",),\n        )\n        secondary_dns = get_env(\n            \"FOS_MGMT_DNS_SECONDARY\",\n            aliases=(\"FTNT_DNS_SECONDARY\",),\n            legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n        )\n        if primary_dns is None:\n            primary_dns = container_dns[0] if container_dns else \"1.1.1.1\"\n        if secondary_dns is None:\n            secondary_dns = container_dns[1] if len(container_dns) > 1 else \"8.8.8.8\"\n        self.mgmt_dns_primary = primary_dns\n        self.mgmt_dns_secondary = secondary_dns\n        self.mgmt_dns_protocol = get_env(\"FTNT_DNS_PROTOCOL\", \"cleartext\")\n        self.terminal = Terminal(self.tn, self.logger, default_wait=self.wait_pattern)\n        desired_password = DEFAULT_PASSWORD if password is None else password\n        self._bootstrap_username = DEFAULT_USERNAME\n        self._bootstrap_password = DEF_POLICY_COMPLIANT_PASSWORD\n        self.credentials = Credentials(self._bootstrap_username, self._bootstrap_password)\n        self.desired_credentials = Credentials(username or DEFAULT_USERNAME, desired_password)\n        self.commander = FOSCommander(\n            terminal=self.terminal,\n            logger=self.logger,\n            continue_on_error=not self._exit_on_bootstrap_error,\n        )\n        self.fos_version = None\n        self.fos_product = None\n        self.driver = FOSCliDriver(\n            self.terminal,\n            self.commander,\n            self.credentials,\n            self.logger,\n            self._bootstrap_password,\n            self.activate_blank_credentials,\n            self.activate_bootstrap_credentials,\n            # Always retry the last accepted credentials after a desired\n            # password transition is rejected. The bootstrap error policy\n            # controls feature failures, not whether the console can recover.\n            allow_credential_recovery=True,\n        )\n        configure_dns = ConfigureMgmtDns(self, self.commander)\n        license_validation = WaitForLicenseValidation(self, self.commander)\n        self._features = [\n            ImageInfo(self, self.commander),\n            ValidateProduct(self, self.commander, expected_product),\n            FormatDisks(self, self.commander),\n            CredentialsFeature(self, self.commander),\n            ConfigureMgmtNetwork(self, self.commander),\n            configure_dns,\n            ConfigureFortiGuardHooks(self, self.commander),\n            SetLicense(self, self.commander),\n            ReapplyFortiGuardHooks(self, self.commander),\n            DefaultConfig(self, self.commander),\n            ReconfigureMgmtNetwork(self, self.commander),\n            license_validation,\n            WaitForFortiTokens(self, self.commander, license_validation),\n            InstallPkiCertificates(self, self.commander),\n            MoveMgmtToVrf1(self, self.commander),\n            ConfigSaveFeature(self, self.commander),\n            ApplyStartupConfig(self, self.commander),\n        ]\n        self._features = apply_debug_feature_cutoff(\n            self._features,\n            get_env(\"FOS_DEBUG_FEATURE\"),\n            self.logger,\n        )\n        self._file_watcher = FeatureFileWatcher(self._features, self.logger)\n        self.commander.start(self._features)\n        vrnetlab.run_command(\n            [\"qemu-img\", \"create\", \"-f\", \"qcow2\", \"empty.qcow2\", \"30G\"]\n        )\n\n        # Comma-separated list of disk sizes to install in the machine. as accepted by qemu-img create.\n        disk_specs = get_env(\"FOS_DISK_SPECS\", \"\").split(\",\")\n        if disk_specs[0] == '':\n            self.logger.warning(\n                \"No additional disks configured. Use FOS_DISK_SPECS to specify a comma-separated list of disk sizes\")\n            return\n        index = 0\n        for spec in disk_specs:\n            index += 1\n            # set up the extra empty disk image\n            # for fortigate logs\n            vrnetlab.run_command(\n                [\"qemu-img\", \"create\", \"-f\", \"qcow2\", f\"empty{index}.qcow2\", spec]\n            )\n\n            self.qemu_args.extend(\n                [\n                    \"-drive\",\n                    f\"if=virtio,format=qcow2,file=empty{index}.qcow2,index={index}\",\n                ]\n            )\n\n            index += 1\n\n    def bootstrap_spin(self):\n        \"\"\"This function should be called periodically to do work.\n\n        returns False when it has failed and given up, otherwise True\n        \"\"\"\n        if self._bootstrap_error is not None:\n            return False\n        try:\n            self.driver.process_state()\n        except KernelPanicError:\n            self.stop()\n            raise\n        except Exception as error:\n            if self._exit_on_bootstrap_error or self.commander.startup_complete:\n                self.stop()\n                raise\n            failed_work = self.commander.continue_after_error(\n                error,\n                at_command_prompt=self.driver.at_command_prompt,\n            )\n            if failed_work is not None:\n                self.logger.exception(\n                    \"Bootstrap work %s failed; continuing with remaining features \"\n                    \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n                    failed_work,\n                )\n                return True\n            self._bootstrap_error = error\n            self.logger.exception(\n                \"Bootstrap cannot continue safely; keeping the VM running for manual \"\n                \"repair because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\"\n            )\n            try:\n                self.terminal.close()\n                self.logger.info(\n                    \"Released the launcher's serial Telnet connection after bootstrap stopped\"\n                )\n            except Exception:\n                self.logger.exception(\n                    \"Failed to release the serial Telnet connection after bootstrap stopped\"\n                )\n            return False\n        if self.driver.ready and not self.commander.feature_errors:\n            self.running = True\n        return True\n\n    def work(self):\n        self._write_heartbeat()\n        super().work()\n        if self.running:\n            self._file_watcher.poll()\n            if not self.driver.ready:\n                self.bootstrap_spin()\n\n    def _write_heartbeat(self):\n        \"\"\"Append one byte to the healthcheck heartbeat file.\n\n        ``fos_healthcheck.py`` blocks in \"starting\" as long as this file\n        keeps growing, so a slow but progressing bootstrap never trips the\n        Docker unhealthy threshold. A wedged launcher stops beating and the\n        probe reports failure. Best-effort: a heartbeat write must never\n        take down the main loop.\n        \"\"\"\n        try:\n            with open(HEARTBEAT_FILE, \"a\") as heartbeat_handle:\n                heartbeat_handle.write(\"\\n\")\n        except OSError:\n            self.logger.debug(\"Failed to write healthcheck heartbeat\", exc_info=True)\n\n    def connect_serial_console(self):\n        try:\n            self.terminal.close()\n        except Exception:\n            pass\n\n        for attempt in range(1, vrnetlab.MAX_RETRIES + 1):\n            try:\n                self.tn.open()\n                break\n            except Exception:\n                if attempt == vrnetlab.MAX_RETRIES:\n                    self.logger.exception(\"Failed to connect to VM serial port.\")\n                    self.stop()\n                    raise\n                self.logger.error(\n                    f\"Unable to connect to VM serial port {5000 + self.num}, \"\n                    f\"retrying in a second (attempt {attempt})\"\n                )\n                time.sleep(1)\n\n        self.stopped = False\n        self.terminal.write(b\"\\r\")\n\n    def activate_desired_credentials(self):\n        self.driver.remember_current_credentials()\n        self.credentials.username = self.desired_credentials.username\n        self.credentials.password = self.desired_credentials.password\n\n    def activate_bootstrap_credentials(self):\n        self.credentials.username = self._bootstrap_username\n        self.credentials.password = self._bootstrap_password\n\n    def activate_blank_credentials(self):\n        self.credentials.password = \"\"\n\n    def gen_mgmt(self):\n        return self._mgmt_net.gen_mgmt(self)\n\n    @staticmethod\n    def mgmt_gateway_destination(gateway, mgmt_address):\n        _address, separator, prefix = str(mgmt_address).partition(\"/\")\n        if separator and prefix:\n            return f\"{gateway}/{prefix}\"\n        return f\"{gateway}/{'128' if ':' in str(gateway) else '32'}\"\n\n    def stop(self):\n        self.stopped = True\n        super().stop()\n\n\nclass FortiOS(vrnetlab.VR):\n    def __init__(self, hostname, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n                 expected_product=\"FortiGate\"):\n        super(FortiOS, self).__init__(username, password, mgmt_passthrough=mgmt_net.mgmt_passthrough)\n        self.logger.debug(\"Hostname\")\n        self.logger.debug(hostname)\n        self.vms = [FortiOS_vm(hostname, username, password, conn_mode, mgmt_net=mgmt_net,\n                               expected_product=expected_product)]\n\n\ndef main(expected_product=\"FortiGate\"):\n\n    parser = argparse.ArgumentParser(description=\"\")\n    parser.add_argument(\n        \"--trace\", action=\"store_true\", help=\"enable trace level logging\"\n    )\n    parser.add_argument(\"--hostname\", default=\"vr-fortinet\", help=\"Fortinet hostname\")\n    parser.add_argument(\"--username\", default=None, help=\"Username\")\n    parser.add_argument(\"--password\", default=None, help=\"Password\", nargs=\"?\")\n    parser.add_argument(\n        \"--connection-mode\",\n        default=\"tc\",\n        help=\"Connection mode to use in the datapath\",\n    )\n    args = parser.parse_args()\n\n    LOG_FORMAT = \"%(asctime)s: %(module)-10s %(levelname)-8s %(message)s\"\n    logging.basicConfig(format=LOG_FORMAT)\n    logger = logging.getLogger()\n\n    logger.setLevel(parse_log_level(get_env(\"FOS_LOG_LEVEL\")))\n\n    mgmt_passthrough = (\n        os.environ.get(\"CLAB_MGMT_PASSTHROUGH\", \"\").lower() == \"true\"\n        if os.environ.get(\"CLAB_MGMT_PASSTHROUGH\")\n        else MGMT_PASSTHROUGH_DEFAULT\n    )\n\n    tftp_server = None\n    mgmt_net = None\n    if mgmt_passthrough:\n        mgmt_net = PassthroughRedirect([f\"udp:{TFTP_PORT}\", f\"udp:{'-'.join(map(str, TFTP_TID_RANGE))}\"])\n        mgmt_net.prep()\n        tftp_server = TFTPServer(mgmt_net=mgmt_net,\n                                 srv_port=TFTP_PORT,\n                                 tid_range=TFTP_TID_RANGE,\n                                 directory=TFTP_DIRECTORY)\n    else:\n        mgmt_net = HostForwardedBridge()\n        mgmt_net.prep()\n        tftp_server = TFTPServer(srv_port=TFTP_PORT,\n                                 mgmt_net=mgmt_net,\n                                 directory=TFTP_DIRECTORY)\n\n    vr = FortiOS(\n        args.hostname, args.username, args.password, conn_mode=args.connection_mode,\n        mgmt_net=mgmt_net, expected_product=expected_product\n    )\n    tftp_server.launch()\n    vrnetlab.boot_delay()\n    vr.start()\n\n\nif __name__ == \"__main__\":\n    main(get_env(\"FOS_EXPECTED_PRODUCT\", \"FortiGate\"))",
        "lineStart": 1,
        "lineEnd": 506,
        "totalLines": 506,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716377001,
      "end": 1793716377006
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_admin_credentials.py"
}

Output

<path>/source/head/fortinet/tests/test_common_admin_credentials.py</path>
<type>file</type>
<content>
1: """Admin credential commits followed by logout and console authentication."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from types import SimpleNamespace
7: from unittest.mock import MagicMock, patch
8: 
9: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
10: 
11: from fortinet.common.common import Credentials
12: from fortinet.common.features.credentials import CredentialsFeature
13: from fortinet.common.fos_cli_driver import FOSCliDriver
14: from fortinet.common.fos_commander import FOSCommander
15: from fortinet.common.terminal import Terminal
16: from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection
17: 
18: 
19: LOGIN = b"fw login:\r\n"
20: READY = b"Welcome!\r\nfw #\r\n"
21: ADMIN_PROMPT = b"fw (admin) #\r\n"
22: 
23: 
24: class AdminCredentialsTests(unittest.TestCase):
25:     def make_stack(self, *, password="newpass", username="admin",
26:                    auto_logout=None, authenticate=True, reject=False,
27:                    exit_works=True):
28:         logger = MagicMock()
29:         policy_prompt = b"fw (password-policy) #\r\n"
30:         old_password_responses = [READY]
31:         if password:
32:             old_password_responses.append(ADMIN_PROMPT)
33:         old_password_responses.append(b"Login incorrect\r\n" + LOGIN)
34:         end_count = 0
35: 
36:         def end_response():
37:             nonlocal end_count
38:             end_count += 1
39:             return LOGIN if auto_logout == "end" and end_count == 2 else b"fw #\r\n"
40: 
41:         login_reply = None if not authenticate else (
42:             b"Login incorrect\r\n" + LOGIN if reject else READY
43:         )
44:         responses = {
45:             b"admin\r": b"Password:",
46:             b"oldpass\r": lambda: old_password_responses.pop(0),
47:             b"config system password-policy\r": policy_prompt,
48:             b"set status disable\r": policy_prompt,
49:             b"config system admin\r": ADMIN_PROMPT,
50:             f"edit {username}\r".encode(): ADMIN_PROMPT,
51:             b"set accprofile super_admin\r": ADMIN_PROMPT,
52:             b"next\r": LOGIN if auto_logout == "next" else ADMIN_PROMPT,
53:             b"end\r": end_response,
54:             b"exit\r": LOGIN if exit_works else b"fw #\r\n",
55:             b"probe\r": b"fw #\r\n",
56:             (password + "\r").encode(): login_reply,
57:         }
58:         if username != "admin":
59:             responses[(username + "\r").encode()] = b"Password:"
60:         if password:
61:             responses[f"set password {password}\r".encode()] = (
62:                 b"Please enter current administrator password: "
63:             )
64:         else:
65:             responses[b"unset password\r"] = ADMIN_PROMPT
66: 
67:         connection = SerialConnection(responses)
68:         terminal = Terminal(connection, logger)
69:         commander = FOSCommander(terminal, logger)
70:         credentials = Credentials("admin", "oldpass")
71:         driver = FOSCliDriver(
72:             terminal, commander, credentials, logger, "bootstrap",
73:             MagicMock(), MagicMock(), allow_credential_recovery=True,
74:         )
75: 
76:         def activate_desired():
77:             driver.remember_current_credentials()
78:             credentials.username = username
79:             credentials.password = password
80: 
81:         vm = SimpleNamespace(
82:             desired_credentials=Credentials(username, password),
83:             activate_desired_credentials=activate_desired,
84:         )
85:         admin = CredentialsFeature(vm, commander)
86:         following = RecordingFeature(commander, "following", ["probe"])
87:         commander.start([admin, following])
88:         self.addCleanup(lambda: terminal.close() if not connection.closed else None)
89:         return connection, commander, driver, admin, following
90: 
91:     def run_driver(self, driver):
92:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
93:                 patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.15):
94:             driver.process_state()
95: 
96:     def test_logout_and_relogin_after_committing_credentials(self):
97:         for username, password in (("admin", "newpass"), ("admin", ""),
98:                                    ("operator", "newpass")):
99:             with self.subTest(username=username, password_set=bool(password)):
100:                 conn, cmd, driver, admin, following = self.make_stack(
101:                     username=username, password=password,
102:                 )
103:                 self.run_driver(driver)
104:                 self.assertTrue(cmd.ready)
105:                 self.assertTrue(admin.completed)
106:                 self.assertTrue(following.completed)
107:                 logout = conn.writes.index(b"exit\r")
108:                 self.assertEqual(conn.writes[logout - 1], b"end\r")
109:                 self.assertEqual(conn.writes[logout + 1:], [
110:                     (username + "\r").encode(),
111:                     (password + "\r").encode(),
112:                     b"probe\r",
113:                 ])
114:                 self.assertEqual(conn.writes.count(b"exit\r"), 1)
115: 
116:     def test_later_features_wait_for_authentication(self):
117:         conn, cmd, driver, admin, following = self.make_stack(authenticate=False)
118:         self.run_driver(driver)
119:         self.assertIn(b"exit\r", conn.writes)
120:         self.assertIn(b"newpass\r", conn.writes)
121:         self.assertNotIn(b"probe\r", conn.writes)
122:         self.assertFalse(admin.completed)
123:         self.assertFalse(following.completed)
124:         self.assertFalse(cmd.ready)
125: 
126:     def test_fortios_logout_at_commit_does_not_replay_password_change(self):
127:         for commit_command in ("next", "end"):
128:             with self.subTest(commit_command=commit_command):
129:                 conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)
130:                 self.run_driver(driver)
131:                 self.assertTrue(cmd.ready)
132:                 self.assertTrue(admin.completed)
133:                 self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
134:                 self.assertEqual(conn.writes.count(b"exit\r"), 1)
135:                 self.assertEqual(conn.writes.count(b"newpass\r"), 2)
136: 
137:     def test_logout_must_return_to_login(self):
138:         conn, _, driver, admin, _ = self.make_stack(exit_works=False)
139:         with self.assertRaisesRegex(RuntimeError, "expected PROVIDE_USERNAME"):
140:             self.run_driver(driver)
141:         self.assertFalse(admin.completed)
142:         self.assertNotIn(b"probe\r", conn.writes)
143: 
144:     def test_rejected_credentials_do_not_start_later_features(self):
145:         conn, _, driver, admin, _ = self.make_stack(reject=True)
146:         with self.assertRaisesRegex(RuntimeError, "Credential rejected"):
147:             self.run_driver(driver)
148:         self.assertFalse(admin.completed)
149:         self.assertNotIn(b"probe\r", conn.writes)
150:         self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
151: 
152: 
153: if __name__ == "__main__":
154:     unittest.main()

(End of file - total 154 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3d5d9001uGUXWaNwmrtar5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3cdf8001xPjYsI2LzMUvLt",
  "callID": "call_5f5f8ee276064c938b20b477",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_admin_credentials.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_admin_credentials.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from types import SimpleNamespace\n7: from unittest.mock import MagicMock, patch\n8: \n9: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n10: \n11: from fortinet.common.common import Credentials\n12: from fortinet.common.features.credentials import CredentialsFeature\n13: from fortinet.common.fos_cli_driver import FOSCliDriver\n14: from fortinet.common.fos_commander import FOSCommander\n15: from fortinet.common.terminal import Terminal\n16: from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n17: \n18: \n19: LOGIN = b\"fw login:\\r\\n\"\n20: READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n21: ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n22: \n23: \n24: class AdminCredentialsTests(unittest.TestCase):\n25:     def make_stack(self, *, password=\"newpass\", username=\"admin\",\n26:                    auto_logout=None, authenticate=True, reject=False,\n27:                    exit_works=True):\n28:         logger = MagicMock()\n29:         policy_prompt = b\"fw (password-policy) #\\r\\n\"\n30:         old_password_responses = [READY]\n31:         if password:\n32:             old_password_responses.append(ADMIN_PROMPT)\n33:         old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n34:         end_count = 0\n35: \n36:         def end_response():\n37:             nonlocal end_count\n38:             end_count += 1\n39:             return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n40: \n41:         login_reply = None if not authenticate else (\n42:             b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n43:         )\n44:         responses = {\n45:             b\"admin\\r\": b\"Password:\",\n46:             b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n47:             b\"config system password-policy\\r\": policy_prompt,\n48:             b\"set status disable\\r\": policy_prompt,\n49:             b\"config system admin\\r\": ADMIN_PROMPT,\n50:             f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n51:             b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n52:             b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n53:             b\"end\\r\": end_response,\n54:             b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n55:             b\"probe\\r\": b\"fw #\\r\\n\",\n56:             (password + \"\\r\").encode(): login_reply,\n57:         }\n58:         if username != \"admin\":\n59:             responses[(username + \"\\r\").encode()] = b\"Password:\"\n60:         if password:\n61:             responses[f\"set password {password}\\r\".encode()] = (\n62:                 b\"Please enter current administrator password: \"\n63:             )\n64:         else:\n65:             responses[b\"unset password\\r\"] = ADMIN_PROMPT\n66: \n67:         connection = SerialConnection(responses)\n68:         terminal = Terminal(connection, logger)\n69:         commander = FOSCommander(terminal, logger)\n70:         credentials = Credentials(\"admin\", \"oldpass\")\n71:         driver = FOSCliDriver(\n72:             terminal, commander, credentials, logger, \"bootstrap\",\n73:             MagicMock(), MagicMock(), allow_credential_recovery=True,\n74:         )\n75: \n76:         def activate_desired():\n77:             driver.remember_current_credentials()\n78:             credentials.username = username\n79:             credentials.password = password\n80: \n81:         vm = SimpleNamespace(\n82:             desired_credentials=Credentials(username, password),\n83:             activate_desired_credentials=activate_desired,\n84:         )\n85:         admin = CredentialsFeature(vm, commander)\n86:         following = RecordingFeature(commander, \"following\", [\"probe\"])\n87:         commander.start([admin, following])\n88:         self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n89:         return connection, commander, driver, admin, following\n90: \n91:     def run_driver(self, driver):\n92:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n93:                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n94:             driver.process_state()\n95: \n96:     def test_logout_and_relogin_after_committing_credentials(self):\n97:         for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n98:                                    (\"operator\", \"newpass\")):\n99:             with self.subTest(username=username, password_set=bool(password)):\n100:                 conn, cmd, driver, admin, following = self.make_stack(\n101:                     username=username, password=password,\n102:                 )\n103:                 self.run_driver(driver)\n104:                 self.assertTrue(cmd.ready)\n105:                 self.assertTrue(admin.completed)\n106:                 self.assertTrue(following.completed)\n107:                 logout = conn.writes.index(b\"exit\\r\")\n108:                 self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n109:                 self.assertEqual(conn.writes[logout + 1:], [\n110:                     (username + \"\\r\").encode(),\n111:                     (password + \"\\r\").encode(),\n112:                     b\"probe\\r\",\n113:                 ])\n114:                 self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n115: \n116:     def test_later_features_wait_for_authentication(self):\n117:         conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n118:         self.run_driver(driver)\n119:         self.assertIn(b\"exit\\r\", conn.writes)\n120:         self.assertIn(b\"newpass\\r\", conn.writes)\n121:         self.assertNotIn(b\"probe\\r\", conn.writes)\n122:         self.assertFalse(admin.completed)\n123:         self.assertFalse(following.completed)\n124:         self.assertFalse(cmd.ready)\n125: \n126:     def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n127:         for commit_command in (\"next\", \"end\"):\n128:             with self.subTest(commit_command=commit_command):\n129:                 conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n130:                 self.run_driver(driver)\n131:                 self.assertTrue(cmd.ready)\n132:                 self.assertTrue(admin.completed)\n133:                 self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n134:                 self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n135:                 self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n136: \n137:     def test_logout_must_return_to_login(self):\n138:         conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n139:         with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n140:             self.run_driver(driver)\n141:         self.assertFalse(admin.completed)\n142:         self.assertNotIn(b\"probe\\r\", conn.writes)\n143: \n144:     def test_rejected_credentials_do_not_start_later_features(self):\n145:         conn, _, driver, admin, _ = self.make_stack(reject=True)\n146:         with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n147:             self.run_driver(driver)\n148:         self.assertFalse(admin.completed)\n149:         self.assertNotIn(b\"probe\\r\", conn.writes)\n150:         self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n151: \n152: \n153: if __name__ == \"__main__\":\n154:     unittest.main()\n\n(End of file - total 154 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_admin_credentials.py",
    "metadata": {
      "preview": "\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom unittest.mock import MagicMock, patch\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.common import Credentials\nfrom fortinet.common.features.credentials import CredentialsFeature\nfrom fortinet.common.fos_cli_driver import FOSCliDriver\nfrom fortinet.common.fos_commander import FOSCommander\nfrom fortinet.common.terminal import Terminal\nfrom fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n\n\nLOGIN = b\"fw login:\\r\\n\"\nREADY = b\"Welcome!\\r\\nfw #\\r\\n\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_admin_credentials.py",
        "text": "\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom unittest.mock import MagicMock, patch\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.common import Credentials\nfrom fortinet.common.features.credentials import CredentialsFeature\nfrom fortinet.common.fos_cli_driver import FOSCliDriver\nfrom fortinet.common.fos_commander import FOSCommander\nfrom fortinet.common.terminal import Terminal\nfrom fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n\n\nLOGIN = b\"fw login:\\r\\n\"\nREADY = b\"Welcome!\\r\\nfw #\\r\\n\"\nADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n\n\nclass AdminCredentialsTests(unittest.TestCase):\n    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n                   auto_logout=None, authenticate=True, reject=False,\n                   exit_works=True):\n        logger = MagicMock()\n        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n        old_password_responses = [READY]\n        if password:\n            old_password_responses.append(ADMIN_PROMPT)\n        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n        end_count = 0\n\n        def end_response():\n            nonlocal end_count\n            end_count += 1\n            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n\n        login_reply = None if not authenticate else (\n            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n        )\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n            b\"config system password-policy\\r\": policy_prompt,\n            b\"set status disable\\r\": policy_prompt,\n            b\"config system admin\\r\": ADMIN_PROMPT,\n            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n            b\"end\\r\": end_response,\n            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n            b\"probe\\r\": b\"fw #\\r\\n\",\n            (password + \"\\r\").encode(): login_reply,\n        }\n        if username != \"admin\":\n            responses[(username + \"\\r\").encode()] = b\"Password:\"\n        if password:\n            responses[f\"set password {password}\\r\".encode()] = (\n                b\"Please enter current administrator password: \"\n            )\n        else:\n            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n\n        connection = SerialConnection(responses)\n        terminal = Terminal(connection, logger)\n        commander = FOSCommander(terminal, logger)\n        credentials = Credentials(\"admin\", \"oldpass\")\n        driver = FOSCliDriver(\n            terminal, commander, credentials, logger, \"bootstrap\",\n            MagicMock(), MagicMock(), allow_credential_recovery=True,\n        )\n\n        def activate_desired():\n            driver.remember_current_credentials()\n            credentials.username = username\n            credentials.password = password\n\n        vm = SimpleNamespace(\n            desired_credentials=Credentials(username, password),\n            activate_desired_credentials=activate_desired,\n        )\n        admin = CredentialsFeature(vm, commander)\n        following = RecordingFeature(commander, \"following\", [\"probe\"])\n        commander.start([admin, following])\n        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n        return connection, commander, driver, admin, following\n\n    def run_driver(self, driver):\n        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n            driver.process_state()\n\n    def test_logout_and_relogin_after_committing_credentials(self):\n        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n                                   (\"operator\", \"newpass\")):\n            with self.subTest(username=username, password_set=bool(password)):\n                conn, cmd, driver, admin, following = self.make_stack(\n                    username=username, password=password,\n                )\n                self.run_driver(driver)\n                self.assertTrue(cmd.ready)\n                self.assertTrue(admin.completed)\n                self.assertTrue(following.completed)\n                logout = conn.writes.index(b\"exit\\r\")\n                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n                self.assertEqual(conn.writes[logout + 1:], [\n                    (username + \"\\r\").encode(),\n                    (password + \"\\r\").encode(),\n                    b\"probe\\r\",\n                ])\n                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n\n    def test_later_features_wait_for_authentication(self):\n        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n        self.run_driver(driver)\n        self.assertIn(b\"exit\\r\", conn.writes)\n        self.assertIn(b\"newpass\\r\", conn.writes)\n        self.assertNotIn(b\"probe\\r\", conn.writes)\n        self.assertFalse(admin.completed)\n        self.assertFalse(following.completed)\n        self.assertFalse(cmd.ready)\n\n    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n        for commit_command in (\"next\", \"end\"):\n            with self.subTest(commit_command=commit_command):\n                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n                self.run_driver(driver)\n                self.assertTrue(cmd.ready)\n                self.assertTrue(admin.completed)\n                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n\n    def test_logout_must_return_to_login(self):\n        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n            self.run_driver(driver)\n        self.assertFalse(admin.completed)\n        self.assertNotIn(b\"probe\\r\", conn.writes)\n\n    def test_rejected_credentials_do_not_start_later_features(self):\n        conn, _, driver, admin, _ = self.make_stack(reject=True)\n        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n            self.run_driver(driver)\n        self.assertFalse(admin.completed)\n        self.assertNotIn(b\"probe\\r\", conn.writes)\n        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 154,
        "totalLines": 154,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716377052,
      "end": 1793716377065
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_recovery.py"
}

Output

<path>/source/head/fortinet/tests/test_common_recovery.py</path>
<type>file</type>
<content>
1: """Bounded recovery after a scope exit or an interrupted CLI session."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from unittest.mock import MagicMock
7: 
8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
9: 
10: from fortinet.common.cli_commands import (  # noqa: E402
11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,
12:     EditBlock, SessionLossAction,
13: )
14: from fortinet.common.common import FOSCliState  # noqa: E402
15: from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402
16: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
17: from fortinet.common.terminal import Data  # noqa: E402
18: 
19: 
20: IP_COMMAND = "set ip 10.0.52.4/24"
21: ACCESS_COMMAND = "set allowaccess ping https ssh http"
22: 
23: 
24: class RecordingFeature(Feature):
25:     def __init__(self, commander, block, context_action=None):
26:         super().__init__(None, commander, "management")
27:         self.block = block
28:         self.context_action = context_action
29:         self.losses = []
30:         self.attempts = []
31:         self.executed = []
32: 
33:     def activate(self):
34:         self.commander.submit_block(self, self.block)
35: 
36:     def on_command_dispatched(self, attempt):
37:         super().on_command_dispatched(attempt)
38:         self.attempts.append(attempt)
39: 
40:     def on_command_executed(self, attempt, state):
41:         self.executed.append(attempt.spec.line)
42: 
43:     def on_context_loss(self, attempt):
44:         self.losses.append(attempt)
45:         if self.context_action is not None:
46:             return self.context_action
47:         return super().on_context_loss(attempt)
48: 
49: 
50: class RecoveryTests(unittest.TestCase):
51:     def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,
52:                        context_action=None, following=False):
53:         terminal = MagicMock()
54:         commander = FOSCommander(terminal, MagicMock(), continue_on_error)
55:         block = ConfigBlock("system interface", [EditBlock("port1", [
56:             ip_command, ACCESS_COMMAND,
57:         ])])
58:         feature = RecordingFeature(commander, block, context_action)
59:         features = [feature]
60:         if following:
61:             features.append(RecordingFeature(
62:                 commander, CommandSequence("following", ["get system status"])
63:             ))
64:         commander.start(features)
65:         return commander, terminal, feature
66: 
67:     def prompt(self, commander, context=None):
68:         scope = f" ({context})" if context else ""
69:         commander.on_state(FOSCliState.CMD_PROMPT, Data(
70:             f"FGT-VM64-KVM-NSVHDM{scope} (Interim)#".encode()
71:         ))
72: 
73:     def enter_interface(self, commander):
74:         self.prompt(commander, "interface")
75:         self.prompt(commander, "port1")
76: 
77:     def finish_interface(self, commander):
78:         self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
79:         self.prompt(commander, "port1")  # allowaccess succeeds; dispatch next.
80:         self.prompt(commander, "interface")  # next succeeds; dispatch end.
81:         self.prompt(commander)  # end succeeds.
82: 
83:     @staticmethod
84:     def writes(terminal):
85:         return [call.args[0] for call in terminal.write.call_args_list]
86: 
87:     def reconnect(self, commander):
88:         commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b"Welcome!"))
89:         self.prompt(commander)
90: 
91:     def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):
92:         commander, terminal, feature = self.make_commander()
93:         self.prompt(commander)
94:         self.enter_interface(commander)
95:         self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.
96:         self.assertEqual(self.writes(terminal), [
97:             "config system interface\r", "edit port1\r", IP_COMMAND + "\r",
98:             "config system interface\r",
99:         ])
100:         self.assertNotIn(IP_COMMAND, feature.executed)
101:         self.assertEqual(feature.losses[0].prompt_context_before, ("port1", "Interim"))
102:         self.assertEqual(feature.losses[0].prompt_context_after, ("Interim",))
103:         self.enter_interface(commander)
104:         self.finish_interface(commander)
105:         ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]
106:         self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])
107:         self.assertTrue(feature.completed)
108:         self.assertTrue(commander.ready)
109: 
110:     def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):
111:         for best_effort in (False, True):
112:             with self.subTest(best_effort=best_effort):
113:                 commander, terminal, feature = self.make_commander(
114:                     continue_on_error=best_effort, following=True,
115:                 )
116:                 self.prompt(commander)
117:                 self.enter_interface(commander)
118:                 self.prompt(commander)
119:                 self.enter_interface(commander)
120:                 if best_effort:
121:                     self.prompt(commander)
122:                     self.assertIn("retry limit", commander.feature_errors[0][1])
123:                     self.assertEqual(self.writes(terminal)[-1], "get system status\r")
124:                 else:
125:                     with self.assertRaisesRegex(RuntimeError, "retry limit"):
126:                         self.prompt(commander)
127:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
128:                 self.assertNotIn(ACCESS_COMMAND + "\r", self.writes(terminal))
129:                 self.assertFalse(feature.completed)
130: 
131:     def test_session_and_context_loss_share_the_same_command_retry_allowance(self):
132:         commander, terminal, feature = self.make_commander()
133:         self.prompt(commander)
134:         self.enter_interface(commander)
135:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
136:         self.reconnect(commander)
137:         self.enter_interface(commander)
138:         with self.assertRaisesRegex(RuntimeError, "retry limit"):
139:             self.prompt(commander)
140:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
141:         self.assertEqual(feature.losses[0].retry_count, 1)
142: 
143:     def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):
144:         commander, terminal, _feature = self.make_commander(
145:             continue_on_error=True, following=True,
146:         )
147:         self.prompt(commander)
148:         self.enter_interface(commander)
149:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
150:         self.reconnect(commander)
151:         self.enter_interface(commander)
152:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
153:         self.assertNotIn("get system status\r", self.writes(terminal))
154:         self.reconnect(commander)
155:         self.assertEqual(self.writes(terminal)[-1], "get system status\r")
156:         self.assertIn("retry limit", commander.feature_errors[0][1])
157: 
158:     def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):
159:         commander, terminal, _feature = self.make_commander(
160:             continue_on_error=True, following=True,
161:         )
162:         self.prompt(commander)
163:         self.enter_interface(commander)
164:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
165:         self.prompt(commander)  # Successful login returns a prompt, no Welcome.
166:         self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
167:         self.enter_interface(commander)
168:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
169:         self.assertNotIn("get system status\r", self.writes(terminal))
170:         self.prompt(commander)  # Exhaustion is handled at this usable prompt.
171:         self.assertEqual(self.writes(terminal)[-1], "get system status\r")
172:         self.assertIn("retry limit", commander.feature_errors[0][1])
173: 
174:     def test_each_command_position_gets_one_recovery(self):
175:         commander, terminal, feature = self.make_commander()
176:         self.prompt(commander)
177:         self.enter_interface(commander)
178:         self.prompt(commander)  # First loss: IP command.
179:         self.enter_interface(commander)
180:         self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
181:         self.prompt(commander)  # Second loss: allowaccess command.
182:         self.enter_interface(commander)
183:         self.finish_interface(commander)
184:         self.assertTrue(feature.completed)
185:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 3)
186:         self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + "\r"), 2)
187: 
188:     def test_feature_can_decline_replay_without_running_session_loss_callback(self):
189:         for explicit_policy in (False, True):
190:             with self.subTest(explicit_policy=explicit_policy):
191:                 spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)
192:                 commander, terminal, feature = self.make_commander(
193:                     ip_command=IP_COMMAND if explicit_policy else spec,
194:                     context_action=ContextLossAction.FAIL if explicit_policy else None,
195:                 )
196:                 feature.on_session_loss = MagicMock()
197:                 self.prompt(commander)
198:                 self.enter_interface(commander)
199:                 with self.assertRaisesRegex(RuntimeError, "feature declined replay"):
200:                     self.prompt(commander)
201:                 feature.on_session_loss.assert_not_called()
202:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
203: 
204:     def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):
205:         spec = CommandSpec(
206:             IP_COMMAND, session_loss=SessionLossAction.CONTINUE,
207:             context_loss=ContextLossAction.RESTART_BLOCK,
208:         )
209:         commander, _terminal, feature = self.make_commander(ip_command=spec)
210:         feature.on_session_loss = MagicMock()
211:         self.prompt(commander)
212:         self.enter_interface(commander)
213:         self.prompt(commander)
214:         self.enter_interface(commander)
215:         self.finish_interface(commander)
216:         self.assertTrue(feature.completed)
217:         feature.on_session_loss.assert_not_called()
218: 
219:     def test_partial_scope_is_aborted_once_before_replay(self):
220:         commander, terminal, feature = self.make_commander()
221:         self.prompt(commander)
222:         self.enter_interface(commander)
223:         self.prompt(commander, "interface")  # Only the edit context disappeared.
224:         self.assertEqual(self.writes(terminal)[-1], "abort\r")
225:         self.prompt(commander)
226:         self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
227:         self.enter_interface(commander)
228:         self.finish_interface(commander)
229:         self.assertTrue(feature.completed)
230:         self.assertNotIn("abort", feature.executed)
231:         self.assertNotIn("abort", [item.spec.line for item in feature.attempts])
232: 
233:     def test_failed_context_reset_does_not_loop(self):
234:         commander, terminal, _feature = self.make_commander()
235:         self.prompt(commander)
236:         self.enter_interface(commander)
237:         self.prompt(commander, "interface")
238:         with self.assertRaisesRegex(RuntimeError, "Unable to restore CLI context"):
239:             self.prompt(commander, "interface")
240:         self.assertEqual(self.writes(terminal).count("abort\r"), 1)
241:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
242: 
243:     def test_session_loss_during_context_reset_resumes_after_login(self):
244:         commander, terminal, feature = self.make_commander()
245:         self.prompt(commander)
246:         self.enter_interface(commander)
247:         self.prompt(commander, "interface")
248:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
249:         self.reconnect(commander)
250:         self.enter_interface(commander)
251:         self.finish_interface(commander)
252:         self.assertTrue(feature.completed)
253:         self.assertEqual(self.writes(terminal).count("abort\r"), 1)
254: 
255:     def test_cleanup_session_loss_is_bounded(self):
256:         terminal = MagicMock()
257:         commander = FOSCommander(terminal, MagicMock())
258:         feature = RecordingFeature(commander, CommandSequence("work", ["get status"]))
259:         commander.register_cleanup(feature, CleanupAction(
260:             "cleanup", CommandSequence("cleanup", ["get cleanup"]),
261:         ))
262:         commander.start([feature])
263:         self.prompt(commander)
264:         self.prompt(commander)  # Begin cleanup after the feature completes.
265:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
266:         self.reconnect(commander)
267:         with self.assertRaisesRegex(RuntimeError, "retry limit"):
268:             commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
269:         self.assertEqual(self.writes(terminal).count("get cleanup\r"), 2)
270: 
271:     def test_newly_submitted_block_resets_retry_allowance(self):
272:         terminal = MagicMock()
273:         commander = FOSCommander(terminal, MagicMock())
274:         feature = StaticFeature(None, commander, "two-blocks", [
275:             ConfigBlock("system global", ["set alias first"]),
276:             ConfigBlock("system global", ["set alias second"]),
277:         ])
278:         commander.start([feature])
279:         self.prompt(commander)
280:         for _index in range(2):
281:             self.prompt(commander, "global")
282:             self.prompt(commander)  # Lost context: retry this block.
283:             self.prompt(commander, "global")
284:             self.prompt(commander, "global")
285:             self.prompt(commander)  # End this block and start the next one.
286:         self.assertTrue(feature.completed)
287:         self.assertEqual(self.writes(terminal).count("set alias first\r"), 2)
288:         self.assertEqual(self.writes(terminal).count("set alias second\r"), 2)
289: 
290: 
291: if __name__ == "__main__":
292:     unittest.main()

(End of file - total 292 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3d60e001qlatWq50X0GXH5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3cdf8001xPjYsI2LzMUvLt",
  "callID": "call_e3d56bb8506e4547addc2ddd",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_recovery.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_recovery.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from unittest.mock import MagicMock\n7: \n8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n9: \n10: from fortinet.common.cli_commands import (  # noqa: E402\n11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n12:     EditBlock, SessionLossAction,\n13: )\n14: from fortinet.common.common import FOSCliState  # noqa: E402\n15: from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n16: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n17: from fortinet.common.terminal import Data  # noqa: E402\n18: \n19: \n20: IP_COMMAND = \"set ip 10.0.52.4/24\"\n21: ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n22: \n23: \n24: class RecordingFeature(Feature):\n25:     def __init__(self, commander, block, context_action=None):\n26:         super().__init__(None, commander, \"management\")\n27:         self.block = block\n28:         self.context_action = context_action\n29:         self.losses = []\n30:         self.attempts = []\n31:         self.executed = []\n32: \n33:     def activate(self):\n34:         self.commander.submit_block(self, self.block)\n35: \n36:     def on_command_dispatched(self, attempt):\n37:         super().on_command_dispatched(attempt)\n38:         self.attempts.append(attempt)\n39: \n40:     def on_command_executed(self, attempt, state):\n41:         self.executed.append(attempt.spec.line)\n42: \n43:     def on_context_loss(self, attempt):\n44:         self.losses.append(attempt)\n45:         if self.context_action is not None:\n46:             return self.context_action\n47:         return super().on_context_loss(attempt)\n48: \n49: \n50: class RecoveryTests(unittest.TestCase):\n51:     def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n52:                        context_action=None, following=False):\n53:         terminal = MagicMock()\n54:         commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n55:         block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n56:             ip_command, ACCESS_COMMAND,\n57:         ])])\n58:         feature = RecordingFeature(commander, block, context_action)\n59:         features = [feature]\n60:         if following:\n61:             features.append(RecordingFeature(\n62:                 commander, CommandSequence(\"following\", [\"get system status\"])\n63:             ))\n64:         commander.start(features)\n65:         return commander, terminal, feature\n66: \n67:     def prompt(self, commander, context=None):\n68:         scope = f\" ({context})\" if context else \"\"\n69:         commander.on_state(FOSCliState.CMD_PROMPT, Data(\n70:             f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n71:         ))\n72: \n73:     def enter_interface(self, commander):\n74:         self.prompt(commander, \"interface\")\n75:         self.prompt(commander, \"port1\")\n76: \n77:     def finish_interface(self, commander):\n78:         self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n79:         self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n80:         self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n81:         self.prompt(commander)  # end succeeds.\n82: \n83:     @staticmethod\n84:     def writes(terminal):\n85:         return [call.args[0] for call in terminal.write.call_args_list]\n86: \n87:     def reconnect(self, commander):\n88:         commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n89:         self.prompt(commander)\n90: \n91:     def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n92:         commander, terminal, feature = self.make_commander()\n93:         self.prompt(commander)\n94:         self.enter_interface(commander)\n95:         self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n96:         self.assertEqual(self.writes(terminal), [\n97:             \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n98:             \"config system interface\\r\",\n99:         ])\n100:         self.assertNotIn(IP_COMMAND, feature.executed)\n101:         self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n102:         self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n103:         self.enter_interface(commander)\n104:         self.finish_interface(commander)\n105:         ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n106:         self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n107:         self.assertTrue(feature.completed)\n108:         self.assertTrue(commander.ready)\n109: \n110:     def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n111:         for best_effort in (False, True):\n112:             with self.subTest(best_effort=best_effort):\n113:                 commander, terminal, feature = self.make_commander(\n114:                     continue_on_error=best_effort, following=True,\n115:                 )\n116:                 self.prompt(commander)\n117:                 self.enter_interface(commander)\n118:                 self.prompt(commander)\n119:                 self.enter_interface(commander)\n120:                 if best_effort:\n121:                     self.prompt(commander)\n122:                     self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n123:                     self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n124:                 else:\n125:                     with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n126:                         self.prompt(commander)\n127:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n128:                 self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n129:                 self.assertFalse(feature.completed)\n130: \n131:     def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n132:         commander, terminal, feature = self.make_commander()\n133:         self.prompt(commander)\n134:         self.enter_interface(commander)\n135:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n136:         self.reconnect(commander)\n137:         self.enter_interface(commander)\n138:         with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n139:             self.prompt(commander)\n140:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n141:         self.assertEqual(feature.losses[0].retry_count, 1)\n142: \n143:     def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n144:         commander, terminal, _feature = self.make_commander(\n145:             continue_on_error=True, following=True,\n146:         )\n147:         self.prompt(commander)\n148:         self.enter_interface(commander)\n149:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n150:         self.reconnect(commander)\n151:         self.enter_interface(commander)\n152:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n153:         self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n154:         self.reconnect(commander)\n155:         self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n156:         self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n157: \n158:     def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n159:         commander, terminal, _feature = self.make_commander(\n160:             continue_on_error=True, following=True,\n161:         )\n162:         self.prompt(commander)\n163:         self.enter_interface(commander)\n164:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n165:         self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n166:         self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n167:         self.enter_interface(commander)\n168:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n169:         self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n170:         self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n171:         self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n172:         self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n173: \n174:     def test_each_command_position_gets_one_recovery(self):\n175:         commander, terminal, feature = self.make_commander()\n176:         self.prompt(commander)\n177:         self.enter_interface(commander)\n178:         self.prompt(commander)  # First loss: IP command.\n179:         self.enter_interface(commander)\n180:         self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n181:         self.prompt(commander)  # Second loss: allowaccess command.\n182:         self.enter_interface(commander)\n183:         self.finish_interface(commander)\n184:         self.assertTrue(feature.completed)\n185:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n186:         self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n187: \n188:     def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n189:         for explicit_policy in (False, True):\n190:             with self.subTest(explicit_policy=explicit_policy):\n191:                 spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n192:                 commander, terminal, feature = self.make_commander(\n193:                     ip_command=IP_COMMAND if explicit_policy else spec,\n194:                     context_action=ContextLossAction.FAIL if explicit_policy else None,\n195:                 )\n196:                 feature.on_session_loss = MagicMock()\n197:                 self.prompt(commander)\n198:                 self.enter_interface(commander)\n199:                 with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n200:                     self.prompt(commander)\n201:                 feature.on_session_loss.assert_not_called()\n202:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n203: \n204:     def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n205:         spec = CommandSpec(\n206:             IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n207:             context_loss=ContextLossAction.RESTART_BLOCK,\n208:         )\n209:         commander, _terminal, feature = self.make_commander(ip_command=spec)\n210:         feature.on_session_loss = MagicMock()\n211:         self.prompt(commander)\n212:         self.enter_interface(commander)\n213:         self.prompt(commander)\n214:         self.enter_interface(commander)\n215:         self.finish_interface(commander)\n216:         self.assertTrue(feature.completed)\n217:         feature.on_session_loss.assert_not_called()\n218: \n219:     def test_partial_scope_is_aborted_once_before_replay(self):\n220:         commander, terminal, feature = self.make_commander()\n221:         self.prompt(commander)\n222:         self.enter_interface(commander)\n223:         self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n224:         self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n225:         self.prompt(commander)\n226:         self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n227:         self.enter_interface(commander)\n228:         self.finish_interface(commander)\n229:         self.assertTrue(feature.completed)\n230:         self.assertNotIn(\"abort\", feature.executed)\n231:         self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n232: \n233:     def test_failed_context_reset_does_not_loop(self):\n234:         commander, terminal, _feature = self.make_commander()\n235:         self.prompt(commander)\n236:         self.enter_interface(commander)\n237:         self.prompt(commander, \"interface\")\n238:         with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n239:             self.prompt(commander, \"interface\")\n240:         self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n241:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n242: \n243:     def test_session_loss_during_context_reset_resumes_after_login(self):\n244:         commander, terminal, feature = self.make_commander()\n245:         self.prompt(commander)\n246:         self.enter_interface(commander)\n247:         self.prompt(commander, \"interface\")\n248:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n249:         self.reconnect(commander)\n250:         self.enter_interface(commander)\n251:         self.finish_interface(commander)\n252:         self.assertTrue(feature.completed)\n253:         self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n254: \n255:     def test_cleanup_session_loss_is_bounded(self):\n256:         terminal = MagicMock()\n257:         commander = FOSCommander(terminal, MagicMock())\n258:         feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n259:         commander.register_cleanup(feature, CleanupAction(\n260:             \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n261:         ))\n262:         commander.start([feature])\n263:         self.prompt(commander)\n264:         self.prompt(commander)  # Begin cleanup after the feature completes.\n265:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n266:         self.reconnect(commander)\n267:         with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n268:             commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n269:         self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n270: \n271:     def test_newly_submitted_block_resets_retry_allowance(self):\n272:         terminal = MagicMock()\n273:         commander = FOSCommander(terminal, MagicMock())\n274:         feature = StaticFeature(None, commander, \"two-blocks\", [\n275:             ConfigBlock(\"system global\", [\"set alias first\"]),\n276:             ConfigBlock(\"system global\", [\"set alias second\"]),\n277:         ])\n278:         commander.start([feature])\n279:         self.prompt(commander)\n280:         for _index in range(2):\n281:             self.prompt(commander, \"global\")\n282:             self.prompt(commander)  # Lost context: retry this block.\n283:             self.prompt(commander, \"global\")\n284:             self.prompt(commander, \"global\")\n285:             self.prompt(commander)  # End this block and start the next one.\n286:         self.assertTrue(feature.completed)\n287:         self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n288:         self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n289: \n290: \n291: if __name__ == \"__main__\":\n292:     unittest.main()\n\n(End of file - total 292 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_recovery.py",
    "metadata": {
      "preview": "\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n    EditBlock, SessionLossAction,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nIP_COMMAND = \"set ip 10.0.52.4/24\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_recovery.py",
        "text": "\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n    EditBlock, SessionLossAction,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nIP_COMMAND = \"set ip 10.0.52.4/24\"\nACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, block, context_action=None):\n        super().__init__(None, commander, \"management\")\n        self.block = block\n        self.context_action = context_action\n        self.losses = []\n        self.attempts = []\n        self.executed = []\n\n    def activate(self):\n        self.commander.submit_block(self, self.block)\n\n    def on_command_dispatched(self, attempt):\n        super().on_command_dispatched(attempt)\n        self.attempts.append(attempt)\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append(attempt.spec.line)\n\n    def on_context_loss(self, attempt):\n        self.losses.append(attempt)\n        if self.context_action is not None:\n            return self.context_action\n        return super().on_context_loss(attempt)\n\n\nclass RecoveryTests(unittest.TestCase):\n    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n                       context_action=None, following=False):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n            ip_command, ACCESS_COMMAND,\n        ])])\n        feature = RecordingFeature(commander, block, context_action)\n        features = [feature]\n        if following:\n            features.append(RecordingFeature(\n                commander, CommandSequence(\"following\", [\"get system status\"])\n            ))\n        commander.start(features)\n        return commander, terminal, feature\n\n    def prompt(self, commander, context=None):\n        scope = f\" ({context})\" if context else \"\"\n        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n        ))\n\n    def enter_interface(self, commander):\n        self.prompt(commander, \"interface\")\n        self.prompt(commander, \"port1\")\n\n    def finish_interface(self, commander):\n        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n        self.prompt(commander)  # end succeeds.\n\n    @staticmethod\n    def writes(terminal):\n        return [call.args[0] for call in terminal.write.call_args_list]\n\n    def reconnect(self, commander):\n        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n        self.prompt(commander)\n\n    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n        self.assertEqual(self.writes(terminal), [\n            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n            \"config system interface\\r\",\n        ])\n        self.assertNotIn(IP_COMMAND, feature.executed)\n        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n        self.assertTrue(feature.completed)\n        self.assertTrue(commander.ready)\n\n    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n        for best_effort in (False, True):\n            with self.subTest(best_effort=best_effort):\n                commander, terminal, feature = self.make_commander(\n                    continue_on_error=best_effort, following=True,\n                )\n                self.prompt(commander)\n                self.enter_interface(commander)\n                self.prompt(commander)\n                self.enter_interface(commander)\n                if best_effort:\n                    self.prompt(commander)\n                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n                else:\n                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n                        self.prompt(commander)\n                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n                self.assertFalse(feature.completed)\n\n    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        self.enter_interface(commander)\n        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n            self.prompt(commander)\n        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n        self.assertEqual(feature.losses[0].retry_count, 1)\n\n    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n        commander, terminal, _feature = self.make_commander(\n            continue_on_error=True, following=True,\n        )\n        self.prompt(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n        self.reconnect(commander)\n        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n\n    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n        commander, terminal, _feature = self.make_commander(\n            continue_on_error=True, following=True,\n        )\n        self.prompt(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n\n    def test_each_command_position_gets_one_recovery(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander)  # First loss: IP command.\n        self.enter_interface(commander)\n        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n        self.prompt(commander)  # Second loss: allowaccess command.\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n\n    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n        for explicit_policy in (False, True):\n            with self.subTest(explicit_policy=explicit_policy):\n                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n                commander, terminal, feature = self.make_commander(\n                    ip_command=IP_COMMAND if explicit_policy else spec,\n                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n                )\n                feature.on_session_loss = MagicMock()\n                self.prompt(commander)\n                self.enter_interface(commander)\n                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n                    self.prompt(commander)\n                feature.on_session_loss.assert_not_called()\n                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n\n    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n        spec = CommandSpec(\n            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n            context_loss=ContextLossAction.RESTART_BLOCK,\n        )\n        commander, _terminal, feature = self.make_commander(ip_command=spec)\n        feature.on_session_loss = MagicMock()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        feature.on_session_loss.assert_not_called()\n\n    def test_partial_scope_is_aborted_once_before_replay(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n        self.prompt(commander)\n        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        self.assertNotIn(\"abort\", feature.executed)\n        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n\n    def test_failed_context_reset_does_not_loop(self):\n        commander, terminal, _feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander, \"interface\")\n        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n            self.prompt(commander, \"interface\")\n        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n\n    def test_session_loss_during_context_reset_resumes_after_login(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander, \"interface\")\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n\n    def test_cleanup_session_loss_is_bounded(self):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock())\n        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n        commander.register_cleanup(feature, CleanupAction(\n            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n        ))\n        commander.start([feature])\n        self.prompt(commander)\n        self.prompt(commander)  # Begin cleanup after the feature completes.\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n\n    def test_newly_submitted_block_resets_retry_allowance(self):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock())\n        feature = StaticFeature(None, commander, \"two-blocks\", [\n            ConfigBlock(\"system global\", [\"set alias first\"]),\n            ConfigBlock(\"system global\", [\"set alias second\"]),\n        ])\n        commander.start([feature])\n        self.prompt(commander)\n        for _index in range(2):\n            self.prompt(commander, \"global\")\n            self.prompt(commander)  # Lost context: retry this block.\n            self.prompt(commander, \"global\")\n            self.prompt(commander, \"global\")\n            self.prompt(commander)  # End this block and start the next one.\n        self.assertTrue(feature.completed)\n        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 292,
        "totalLines": 292,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716377106,
      "end": 1793716377117
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d3d61f001O0CiDLsAgdoDB6",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3cdf8001xPjYsI2LzMUvLt",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 4909,
    "input": 4722,
    "output": 135,
    "reasoning": 52,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d3cdf8001xPjYsI2LzMUvLt",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716375032,
    "completed": 1793716377121
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 4909,
    "input": 4722,
    "output": 135,
    "reasoning": 52,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 14
step-start
{
  "type": "step-start",
  "id": "prt_1a1d3dc67001oHZ11VCim0hziM",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3d625001pfFAbj0BYyugan"
}
Reasoning
Continue with remaining test files, fos_commander rest, terminal rest, test_common_scope_errors.py, test_common_terminal_driver rest, test_common_stack_parsing rest, test_common_stack_boundaries, features/pki.py diff, READMEs. Let me batch reads.
Now let me read the remaining test files and the rest of the core modules that were truncated earlier.
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_scope_errors.py"
}

Output

<path>/source/head/fortinet/tests/test_common_scope_errors.py</path>
<type>file</type>
<content>
1: """Scope commit failures are mandatory errors, including best-effort commands."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from unittest.mock import MagicMock
7: 
8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
9: 
10: from fortinet.common.cli_commands import (  # noqa: E402
11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,
12: )
13: from fortinet.common.common import FOSCliState  # noqa: E402
14: from fortinet.common.features.base import Feature  # noqa: E402
15: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
16: from fortinet.common.terminal import Data  # noqa: E402
17: 
18: 
19: class RecordingFeature(Feature):
20:     def __init__(self, commander, name, commands):
21:         super().__init__(None, commander, name)
22:         self.commands = commands
23:         self.executed = []
24: 
25:     def activate(self):
26:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))
27: 
28:     def on_command_executed(self, attempt, state):
29:         self.executed.append(attempt.spec.line)
30: 
31: 
32: class ScopeCommitFailureTests(unittest.TestCase):
33:     @staticmethod
34:     def prompt(commander, context=None, output=b""):
35:         scope = f" ({context})" if context else ""
36:         commander.on_state(FOSCliState.CMD_PROMPT, Data(
37:             output + f"fw{scope} #".encode()
38:         ))
39: 
40:     @staticmethod
41:     def writes(terminal):
42:         return [call.args[0] for call in terminal.write.call_args_list]
43: 
44:     def test_closing_failure_cannot_be_disabled_or_replayed(self):
45:         for close in ("next", "end"):
46:             for capture in (False, True):
47:                 for best_effort in (False, True):
48:                     with self.subTest(close=close, capture=capture, best_effort=best_effort):
49:                         terminal = MagicMock()
50:                         commander = FOSCommander(terminal, MagicMock(), best_effort)
51:                         feature = RecordingFeature(commander, "commit", [
52:                             CommandSpec(close, capture_output=capture, fail_on_error=False),
53:                             "set must-not-run 1",
54:                         ])
55:                         feature.on_context_loss = MagicMock()
56:                         following = RecordingFeature(commander, "following", ["get status"])
57:                         commander.start([feature, following])
58:                         self.prompt(commander, "port1")
59:                         # The failure code can span multiple serial reads.
60:                         for chunk in (b"Command fa", b"il. Return co", b"de -542.\r\n"):
61:                             data = Data(chunk)
62:                             commander.on_output(data)
63:                             self.assertTrue(data.discarded)
64:                         if best_effort:
65:                             self.prompt(commander, "interface")
66:                             self.assertEqual(self.writes(terminal), [close + "\r", "get status\r"])
67:                             self.assertEqual(commander.feature_errors[0][0], "commit")
68:                             self.assertIn("return code -542", commander.feature_errors[0][1])
69:                         else:
70:                             with self.assertRaisesRegex(RuntimeError, "return code -542"):
71:                                 self.prompt(commander, "interface")
72:                             self.assertEqual(self.writes(terminal), [close + "\r"])
73:                         feature.on_context_loss.assert_not_called()
74:                         self.assertEqual(feature.executed, [])
75:                         self.assertFalse(feature.completed)
76: 
77:     def test_closing_failure_with_same_prompt_still_ejects(self):
78:         for code in ("0", "7", "-61"):
79:             for suffix in ("", "."):
80:                 with self.subTest(code=code, suffix=suffix):
81:                     terminal = MagicMock()
82:                     commander = FOSCommander(terminal, MagicMock())
83:                     feature = RecordingFeature(commander, "commit", ["next", "end"])
84:                     commander.start([feature])
85:                     self.prompt(commander, "port1")
86:                     with self.assertRaisesRegex(RuntimeError, f"return code {code}"):
87:                         self.prompt(
88:                             commander, "port1",
89:                             f"  Command fail. Return code {code}{suffix}\r\n".encode(),
90:                         )
91:                     self.assertEqual(self.writes(terminal), ["next\r"])
92: 
93:     def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):
94:         for capture in (False, True):
95:             with self.subTest(capture=capture):
96:                 terminal = MagicMock()
97:                 commander = FOSCommander(terminal, MagicMock())
98:                 feature = RecordingFeature(commander, "configure", [
99:                     ConfigBlock("system interface", [EditBlock("port1", [
100:                         CommandSpec("set unsupported 1", capture_output=capture),
101:                     ])]),
102:                 ])
103:                 commander.start([feature])
104:                 self.prompt(commander)
105:                 self.prompt(commander, "interface")
106:                 self.prompt(commander, "port1")
107:                 self.prompt(commander, "port1", b"Command fail. Return code -61.\r\n")
108:                 self.assertEqual(self.writes(terminal)[-1], "next\r")
109:                 self.prompt(commander, "interface")
110:                 self.prompt(commander)
111:                 self.assertTrue(feature.completed)
112:                 self.assertTrue(commander.ready)
113:                 self.assertEqual(commander.feature_errors, ())
114: 
115:     def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):
116:         for best_effort in (False, True):
117:             with self.subTest(best_effort=best_effort):
118:                 terminal = MagicMock()
119:                 commander = FOSCommander(terminal, MagicMock(), best_effort)
120:                 feature = RecordingFeature(commander, "work", ["get initial"])
121:                 following = RecordingFeature(commander, "following", ["get status"])
122:                 commander.register_cleanup(feature, CleanupAction(
123:                     "close", CommandSequence("close", ["end"]),
124:                 ))
125:                 commander.start([feature, following])
126:                 self.prompt(commander)
127:                 self.prompt(commander)
128:                 self.assertEqual(self.writes(terminal)[-1], "end\r")
129:                 if best_effort:
130:                     self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
131:                     self.assertEqual(commander.feature_errors[0][0], "cleanup")
132:                     self.assertEqual(self.writes(terminal)[-1], "get status\r")
133:                 else:
134:                     with self.assertRaisesRegex(RuntimeError, "return code -5"):
135:                         self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
136:                     self.assertNotIn("get status\r", self.writes(terminal))
137: 
138:     def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):
139:         terminal = MagicMock()
140:         commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)
141:         feature = RecordingFeature(commander, "commit", [CommandSpec(
142:             "end", completion_states=(FOSCliState.CONFIRMATION,),
143:             expected_completion_state=FOSCliState.CMD_PROMPT,
144:         )])
145:         commander.start([feature])
146:         self.prompt(commander, "interface")
147:         with self.assertRaisesRegex(RuntimeError, "unexpected prompt"):
148:             commander.on_state(FOSCliState.CONFIRMATION, Data(b"Do you want to continue?"))
149:         self.assertEqual(self.writes(terminal), ["end\r"])
150:         self.assertFalse(feature.completed)
151: 
152: 
153: if __name__ == "__main__":
154:     unittest.main()

(End of file - total 154 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3deb2001DdZGEfDn88q1aF",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3d625001pfFAbj0BYyugan",
  "callID": "call_480e42ddc0b74f7f9baaa855",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_scope_errors.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_scope_errors.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from unittest.mock import MagicMock\n7: \n8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n9: \n10: from fortinet.common.cli_commands import (  # noqa: E402\n11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n12: )\n13: from fortinet.common.common import FOSCliState  # noqa: E402\n14: from fortinet.common.features.base import Feature  # noqa: E402\n15: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n16: from fortinet.common.terminal import Data  # noqa: E402\n17: \n18: \n19: class RecordingFeature(Feature):\n20:     def __init__(self, commander, name, commands):\n21:         super().__init__(None, commander, name)\n22:         self.commands = commands\n23:         self.executed = []\n24: \n25:     def activate(self):\n26:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n27: \n28:     def on_command_executed(self, attempt, state):\n29:         self.executed.append(attempt.spec.line)\n30: \n31: \n32: class ScopeCommitFailureTests(unittest.TestCase):\n33:     @staticmethod\n34:     def prompt(commander, context=None, output=b\"\"):\n35:         scope = f\" ({context})\" if context else \"\"\n36:         commander.on_state(FOSCliState.CMD_PROMPT, Data(\n37:             output + f\"fw{scope} #\".encode()\n38:         ))\n39: \n40:     @staticmethod\n41:     def writes(terminal):\n42:         return [call.args[0] for call in terminal.write.call_args_list]\n43: \n44:     def test_closing_failure_cannot_be_disabled_or_replayed(self):\n45:         for close in (\"next\", \"end\"):\n46:             for capture in (False, True):\n47:                 for best_effort in (False, True):\n48:                     with self.subTest(close=close, capture=capture, best_effort=best_effort):\n49:                         terminal = MagicMock()\n50:                         commander = FOSCommander(terminal, MagicMock(), best_effort)\n51:                         feature = RecordingFeature(commander, \"commit\", [\n52:                             CommandSpec(close, capture_output=capture, fail_on_error=False),\n53:                             \"set must-not-run 1\",\n54:                         ])\n55:                         feature.on_context_loss = MagicMock()\n56:                         following = RecordingFeature(commander, \"following\", [\"get status\"])\n57:                         commander.start([feature, following])\n58:                         self.prompt(commander, \"port1\")\n59:                         # The failure code can span multiple serial reads.\n60:                         for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n61:                             data = Data(chunk)\n62:                             commander.on_output(data)\n63:                             self.assertTrue(data.discarded)\n64:                         if best_effort:\n65:                             self.prompt(commander, \"interface\")\n66:                             self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n67:                             self.assertEqual(commander.feature_errors[0][0], \"commit\")\n68:                             self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n69:                         else:\n70:                             with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n71:                                 self.prompt(commander, \"interface\")\n72:                             self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n73:                         feature.on_context_loss.assert_not_called()\n74:                         self.assertEqual(feature.executed, [])\n75:                         self.assertFalse(feature.completed)\n76: \n77:     def test_closing_failure_with_same_prompt_still_ejects(self):\n78:         for code in (\"0\", \"7\", \"-61\"):\n79:             for suffix in (\"\", \".\"):\n80:                 with self.subTest(code=code, suffix=suffix):\n81:                     terminal = MagicMock()\n82:                     commander = FOSCommander(terminal, MagicMock())\n83:                     feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n84:                     commander.start([feature])\n85:                     self.prompt(commander, \"port1\")\n86:                     with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n87:                         self.prompt(\n88:                             commander, \"port1\",\n89:                             f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n90:                         )\n91:                     self.assertEqual(self.writes(terminal), [\"next\\r\"])\n92: \n93:     def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n94:         for capture in (False, True):\n95:             with self.subTest(capture=capture):\n96:                 terminal = MagicMock()\n97:                 commander = FOSCommander(terminal, MagicMock())\n98:                 feature = RecordingFeature(commander, \"configure\", [\n99:                     ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n100:                         CommandSpec(\"set unsupported 1\", capture_output=capture),\n101:                     ])]),\n102:                 ])\n103:                 commander.start([feature])\n104:                 self.prompt(commander)\n105:                 self.prompt(commander, \"interface\")\n106:                 self.prompt(commander, \"port1\")\n107:                 self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n108:                 self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n109:                 self.prompt(commander, \"interface\")\n110:                 self.prompt(commander)\n111:                 self.assertTrue(feature.completed)\n112:                 self.assertTrue(commander.ready)\n113:                 self.assertEqual(commander.feature_errors, ())\n114: \n115:     def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n116:         for best_effort in (False, True):\n117:             with self.subTest(best_effort=best_effort):\n118:                 terminal = MagicMock()\n119:                 commander = FOSCommander(terminal, MagicMock(), best_effort)\n120:                 feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n121:                 following = RecordingFeature(commander, \"following\", [\"get status\"])\n122:                 commander.register_cleanup(feature, CleanupAction(\n123:                     \"close\", CommandSequence(\"close\", [\"end\"]),\n124:                 ))\n125:                 commander.start([feature, following])\n126:                 self.prompt(commander)\n127:                 self.prompt(commander)\n128:                 self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n129:                 if best_effort:\n130:                     self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n131:                     self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n132:                     self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n133:                 else:\n134:                     with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n135:                         self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n136:                     self.assertNotIn(\"get status\\r\", self.writes(terminal))\n137: \n138:     def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n139:         terminal = MagicMock()\n140:         commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n141:         feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n142:             \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n143:             expected_completion_state=FOSCliState.CMD_PROMPT,\n144:         )])\n145:         commander.start([feature])\n146:         self.prompt(commander, \"interface\")\n147:         with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n148:             commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n149:         self.assertEqual(self.writes(terminal), [\"end\\r\"])\n150:         self.assertFalse(feature.completed)\n151: \n152: \n153: if __name__ == \"__main__\":\n154:     unittest.main()\n\n(End of file - total 154 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_scope_errors.py",
    "metadata": {
      "preview": "\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_scope_errors.py",
        "text": "\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):\n        super().__init__(None, commander, name)\n        self.commands = commands\n        self.executed = []\n\n    def activate(self):\n        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append(attempt.spec.line)\n\n\nclass ScopeCommitFailureTests(unittest.TestCase):\n    @staticmethod\n    def prompt(commander, context=None, output=b\"\"):\n        scope = f\" ({context})\" if context else \"\"\n        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n            output + f\"fw{scope} #\".encode()\n        ))\n\n    @staticmethod\n    def writes(terminal):\n        return [call.args[0] for call in terminal.write.call_args_list]\n\n    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n        for close in (\"next\", \"end\"):\n            for capture in (False, True):\n                for best_effort in (False, True):\n                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n                        terminal = MagicMock()\n                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n                        feature = RecordingFeature(commander, \"commit\", [\n                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n                            \"set must-not-run 1\",\n                        ])\n                        feature.on_context_loss = MagicMock()\n                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n                        commander.start([feature, following])\n                        self.prompt(commander, \"port1\")\n                        # The failure code can span multiple serial reads.\n                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n                            data = Data(chunk)\n                            commander.on_output(data)\n                            self.assertTrue(data.discarded)\n                        if best_effort:\n                            self.prompt(commander, \"interface\")\n                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n                        else:\n                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n                                self.prompt(commander, \"interface\")\n                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n                        feature.on_context_loss.assert_not_called()\n                        self.assertEqual(feature.executed, [])\n                        self.assertFalse(feature.completed)\n\n    def test_closing_failure_with_same_prompt_still_ejects(self):\n        for code in (\"0\", \"7\", \"-61\"):\n            for suffix in (\"\", \".\"):\n                with self.subTest(code=code, suffix=suffix):\n                    terminal = MagicMock()\n                    commander = FOSCommander(terminal, MagicMock())\n                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n                    commander.start([feature])\n                    self.prompt(commander, \"port1\")\n                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n                        self.prompt(\n                            commander, \"port1\",\n                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n                        )\n                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n\n    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n        for capture in (False, True):\n            with self.subTest(capture=capture):\n                terminal = MagicMock()\n                commander = FOSCommander(terminal, MagicMock())\n                feature = RecordingFeature(commander, \"configure\", [\n                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n                    ])]),\n                ])\n                commander.start([feature])\n                self.prompt(commander)\n                self.prompt(commander, \"interface\")\n                self.prompt(commander, \"port1\")\n                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n                self.prompt(commander, \"interface\")\n                self.prompt(commander)\n                self.assertTrue(feature.completed)\n                self.assertTrue(commander.ready)\n                self.assertEqual(commander.feature_errors, ())\n\n    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n        for best_effort in (False, True):\n            with self.subTest(best_effort=best_effort):\n                terminal = MagicMock()\n                commander = FOSCommander(terminal, MagicMock(), best_effort)\n                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n                following = RecordingFeature(commander, \"following\", [\"get status\"])\n                commander.register_cleanup(feature, CleanupAction(\n                    \"close\", CommandSequence(\"close\", [\"end\"]),\n                ))\n                commander.start([feature, following])\n                self.prompt(commander)\n                self.prompt(commander)\n                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n                if best_effort:\n                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n                else:\n                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n\n    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n            expected_completion_state=FOSCliState.CMD_PROMPT,\n        )])\n        commander.start([feature])\n        self.prompt(commander, \"interface\")\n        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n        self.assertFalse(feature.completed)\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 154,
        "totalLines": 154,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716379317,
      "end": 1793716379321
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_terminal_driver.py",
  "offset": 1,
  "limit": 600
}

Output

<path>/source/head/fortinet/tests/test_common_terminal_driver.py</path>
<type>file</type>
<content>
1: """Serial terminal buffering and FortiOS CLI state-machine tests."""
2: 
3: import logging
4: import re
5: import sys
6: import threading
7: import unittest
8: from contextlib import contextmanager
9: from unittest.mock import MagicMock, patch
10: 
11: REPO_ROOT = __import__("pathlib").Path(__file__).resolve().parents[2]
12: sys.path.insert(0, str(REPO_ROOT))
13: 
14: from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402
15: from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402
16: from fortinet.common.fos_cli_driver import (  # noqa: E402
17:     FOSCliDriver,
18:     KernelPanicError,
19: )
20: from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402
21: 
22: 
23: class ByteQueueTests(unittest.TestCase):
24:     def test_put_get_close_timeout_and_failure(self):
25:         queue = _ByteQueue(3)
26:         queue.put(b"abc")
27:         self.assertEqual(queue.get_one(), b"abc")
28:         queue.put(b"def")
29:         self.assertEqual(queue.get(), b"def")
30:         self.assertEqual(queue.get(0), b"")
31:         queue.close()
32:         queue.put(b"ignored")
33:         self.assertEqual(queue.get(), b"")
34:         failed = _ByteQueue(5)
35:         failed.fail(ValueError("read failed"))
36:         with self.assertRaisesRegex(ValueError, "read failed"):
37:             failed.get(0)
38: 
39:     def test_blocked_get_wakes_when_data_arrives(self):
40:         queue = _ByteQueue(10)
41:         result = []
42:         reader = threading.Thread(target=lambda: result.append(queue.get(1)))
43:         reader.start()
44:         queue.put(b"ready")
45:         reader.join(1)
46:         self.assertEqual(result, [b"ready"])
47: 
48: 
49: class TerminalTests(unittest.TestCase):
50:     def terminal_with_data(self, data, limit=100):
51:         terminal = Terminal(MagicMock(), MagicMock())
52:         terminal._buffer_limit = limit
53:         terminal._read_queue = _ByteQueue(limit)
54:         terminal._read_queue.put(data)
55:         terminal._ensure_reader = lambda: None
56:         return terminal
57: 
58:     def test_data_wrapper_and_expect_earliest_match_preserves_tail(self):
59:         view = Data(b"hello")
60:         self.assertTrue(view)
61:         self.assertEqual(len(view), 5)
62:         self.assertIn(b"ell", view)
63:         self.assertEqual(view.decode(), "hello")
64:         self.assertTrue(view.startswith(b"he"))
65:         self.assertEqual(view, b"hello")
66:         terminal = self.terminal_with_data(b"prefix PROMPT trailing")
67:         index, match, output = terminal.expect([b"trailing", b"PROMPT"], timeout=0.1)
68:         self.assertEqual(index, 1)
69:         self.assertEqual(match.group(), b"PROMPT")
70:         self.assertEqual(bytes(output), b"prefix PROMPT")
71:         self.assertEqual(bytes(terminal._buffer), b" trailing")
72:         no_match = self.terminal_with_data(b"abc")
73:         result = no_match.expect([b"never"], timeout=0)
74:         self.assertEqual(result[0:2], (-1, None))
75:         self.assertEqual(bytes(result[2]), b"")
76: 
77:     def test_discard_retained_prefix_and_buffer_limit_error(self):
78:         terminal = self.terminal_with_data(b"output prompt", limit=20)
79:         _, _, _ = terminal.expect([b"prompt"], timeout=0.1)
80:         data = Data(b"output", terminal._discard_prefix)
81:         terminal._buffer = bytearray(b"output trailing")
82:         data.discard(b"output")
83:         self.assertTrue(data.discarded)
84:         self.assertEqual(bytes(terminal._buffer), b" trailing")
85:         data.discard(b"wrong")
86:         terminal._buffer = bytearray(b"123456")
87:         terminal._buffer_limit = 5
88:         with self.assertRaisesRegex(RuntimeError, "exceeded 5"):
89:             terminal._enforce_buffer_limit()
90:         terminal._logger.error.assert_called_once()
91: 
92:     def test_timeout_preserves_partial_token_for_a_later_read(self):
93:         terminal = self.terminal_with_data(b"Login incor")
94:         pattern = rb"(?m)^Login incorrect\r?$"
95:         index, match, output = terminal.expect([pattern], timeout=0.001)
96:         self.assertEqual((index, match), (-1, None))
97:         self.assertEqual(bytes(output), b"Login incor")
98:         # Inspection without discard keeps the partial token, including when
99:         # another wait expires without receiving any more bytes.
100:         _, _, output = terminal.expect([pattern], timeout=0)
101:         self.assertEqual(bytes(output), b"Login incor")
102:         terminal._read_queue.put(b"rect\n")
103:         index, match, output = terminal.expect([pattern], timeout=0.1)
104:         self.assertEqual(index, 0)
105:         self.assertEqual(match.group(), b"Login incorrect")
106:         self.assertEqual(bytes(output), b"Login incorrect")
107:         self.assertEqual(bytes(terminal._buffer), b"\n")
108: 
109:     def test_timeout_inspection_sees_a_token_completed_by_new_input(self):
110:         terminal = self.terminal_with_data(b"Verifying pass")
111:         _, _, output = terminal.expect([b"fw #"], timeout=0.001)
112:         self.assertIsNone(re.search(rb"Verifying password", bytes(output)))
113: 
114:         terminal._read_queue.put(b"word...\n")
115:         _, match, output = terminal.expect([b"fw #"], timeout=0.001)
116:         self.assertIsNone(match)
117:         self.assertIsNotNone(re.search(rb"Verifying password", bytes(output)))
118:         self.assertEqual(bytes(terminal._buffer), b"Verifying password...\n")
119:         output.discard()
120:         self.assertEqual(bytes(terminal._buffer), b"")
121: 
122:     def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):
123:         prefix = b"\nVerifying password...\n"
124:         chunk = b"admin\nadmin\n"
125:         terminal = self.terminal_with_data(chunk)
126:         terminal._buffer.extend(prefix)
127: 
128:         _, _, output = terminal.expect([b"fw #"], timeout=0.001)
129:         self.assertEqual(bytes(output), prefix + chunk)
130:         attempt = CommandAttempt(CommandSpec("end"), 1, 0)
131:         attempt.on_output(output)
132: 
133:         self.assertEqual(bytes(attempt.output), prefix + chunk)
134:         self.assertEqual(bytes(terminal._buffer), b"")
135:         terminal._logger.warning.assert_not_called()
136: 
137:     def test_suppression_is_nested_and_restores_context(self):
138:         @contextmanager
139:         def context():
140:             events.append("enter")
141:             try:
142:                 yield
143:             finally:
144:                 events.append("exit")
145:         events = []
146:         connection = MagicMock()
147:         connection.suppress_output.return_value = context()
148:         terminal = Terminal(connection, MagicMock())
149:         with terminal.suppress_output():
150:             with terminal.suppress_output():
151:                 self.assertEqual(terminal._output_suppression_depth, 2)
152:         self.assertEqual(events, ["enter", "exit"])
153:         self.assertIsNone(terminal._output_suppression_context)
154: 
155:     def test_write_and_close_flushes_writer(self):
156:         connection = MagicMock()
157:         terminal = Terminal(connection, MagicMock())
158:         terminal.write("hello")
159:         terminal.write(b" world")
160:         terminal.close()
161:         written = b"".join(call.args[0] for call in connection.write.call_args_list)
162:         self.assertEqual(written, b"hello world")
163:         connection.close.assert_called_once()
164: 
165:     def test_reader_failure_propagates_and_terminal_buffer_setting(self):
166:         reader = MagicMock()
167:         reader.read_very_eager.side_effect = OSError("serial failed")
168:         logger = MagicMock()
169:         terminal = Terminal(reader, logger)
170:         stop = threading.Event()
171:         queue = _ByteQueue(10)
172:         terminal._read_forever(stop, queue)
173:         with self.assertRaisesRegex(OSError, "serial failed"):
174:             queue.get(0)
175:         logger.exception.assert_called_once()
176:         with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}):
177:             self.assertEqual(terminal_buffer_limit_bytes(), 32)
178:         with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "64", "FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}, clear=True):
179:             self.assertEqual(terminal_buffer_limit_bytes(), 64)
180:         with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "0"}, clear=True):
181:             with self.assertRaises(ValueError):
182:                 terminal_buffer_limit_bytes()
183: 
184:     def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):
185:         for env_name in ("FTNT_LOG_RAW_SERIAL", "FOS_LOG_RAW_SERIAL"):
186:             with self.subTest(env_name=env_name):
187:                 terminal = self.terminal_with_data(b"matched")
188:                 with patch.dict("os.environ", {env_name: "true"}, clear=True):
189:                     terminal.expect([b"matched"], timeout=0.1)
190:                 terminal._logger.log.assert_called_once_with(
191:                     TRACE_LEVEL,
192:                     "buffer: bytearray(b'matched')",
193:                 )
194: 
195: 
196: class DriverTests(unittest.TestCase):
197:     def make_driver(self, *, allow_recovery=False):
198:         terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()
199:         commander.ready = False
200:         creds = Credentials("admin", "old")
201:         blank = MagicMock()
202:         bootstrap = MagicMock()
203:         driver = FOSCliDriver(terminal, commander, creds, logger, "new", blank, bootstrap, allow_recovery)
204:         return driver, terminal, commander, logger, blank, bootstrap
205: 
206:     def test_prompt_patterns_responses_and_state_callbacks(self):
207:         driver, terminal, commander, logger, blank, bootstrap = self.make_driver()
208:         driver.set_prompt_patterns("lab[1]")
209:         self.assertIsNotNone(re.search(driver.state_patterns[FOSCliState.CMD_PROMPT.value], b"lab[1] #"))
210:         self.assertIsNotNone(re.search(driver.state_patterns[FOSCliState.CMD_PROMPT.value], b"lab[1] #\r"))
211:         driver._provide_username()
212:         driver._provide_password()
213:         driver._provide_current_password()
214:         driver._provide_new_password()
215:         driver._confirm_new_password()
216:         driver._continue_pager()
217:         self.assertEqual(terminal.write.call_args_list[0].args[0], b"admin\r")
218:         self.assertEqual(terminal.write.call_args_list[-1].args[0], b" ")
219:         self.assertTrue(driver._pending_bootstrap_activation)
220:         driver._credential_accepted()
221:         bootstrap.assert_called_once()
222:         driver._process_state(FOSCliState.CMD_PROMPT_ECHO, Data(b"hostname # get"))
223:         commander.on_prompt_echo.assert_called_once()
224:         self.assertEqual(commander.on_state.call_count, 0)
225:         driver._process_state(FOSCliState.CMD_PROMPT, Data(b"hostname #"))
226:         commander.tick.assert_called()
227:         driver._last_known_state = FOSCliState.CMD_PROMPT
228:         driver._current_state = FOSCliState.TN_TIMEOUT
229:         driver._process_state(FOSCliState.TN_TIMEOUT, Data(b""))
230:         commander.on_idle_prompt.assert_called_once()
231:         self.assertTrue(driver.at_command_prompt)
232: 
233:     def test_blank_fallback_and_previous_credential_recovery(self):
234:         driver, terminal, commander, logger, blank, bootstrap = self.make_driver(allow_recovery=True)
235:         driver._credential_rejected()
236:         driver._provide_password()
237:         blank.assert_called_once()
238:         self.assertFalse(driver._blank_fallback_available)
239:         self.assertEqual(terminal.write.call_args.args[0], b"\r")
240:         driver.remember_current_credentials()
241:         driver._credential_rejected()
242:         driver._provide_username()
243:         driver._provide_password()
244:         self.assertEqual(terminal.write.call_args_list[-2].args[0], b"admin\r")
245:         self.assertEqual(terminal.write.call_args_list[-1].args[0], b"old\r")
246:         driver._credential_accepted()
247:         commander.record_feature_error.assert_called_once()
248:         driver._credential_accepted()
249:         commander.resolve_feature_error.assert_called_once()
250: 
251:     def test_rejected_and_recovery_credential_branches(self):
252:         driver, terminal, commander, logger, blank, bootstrap = self.make_driver()
253:         driver._initial_login_complete = True
254:         with self.assertRaisesRegex(RuntimeError, "Credential rejected"):
255:             driver._credential_rejected()
256:         driver._license_failed()
257:         driver._last_known_state = FOSCliState.REBOOTING
258:         driver._unknown()
259:         self.assertEqual(driver._idle_spins, 1)
260:         driver._unknown_started_at = 0
261:         with patch("fortinet.common.fos_cli_driver.time.monotonic", side_effect=[31, 32, 64, 65, 96, 97]):
262:             driver._recover_unknown_stall()
263:             driver._recover_unknown_stall()
264:             driver._recover_unknown_stall()
265:         self.assertEqual(terminal.write.call_count, 3)
266:         driver._unknown_newlines = 3
267:         driver._unknown_started_at = 1
268:         with patch("fortinet.common.fos_cli_driver.time.monotonic", return_value=40):
269:             with self.assertRaisesRegex(RuntimeError, "unknown state"):
270:                 driver._recover_unknown_stall()
271:         driver._clear_unknown_stall()
272:         self.assertIsNone(driver._unknown_started_at)
273: 
274:     def test_state_selection_and_timeout_processing(self):
275:         driver, terminal, commander, logger, *_ = self.make_driver()
276:         terminal.expect.return_value = (FOSCliState.PROVIDE_USERNAME.value, re.search(b"login", b"login"), Data(b"login"))
277:         state, output, matched = driver._next_state()
278:         self.assertEqual(state, FOSCliState.PROVIDE_USERNAME)
279:         self.assertTrue(matched)
280:         terminal.expect.return_value = (-1, None, Data(b"noise"))
281:         self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)
282:         terminal.expect.return_value = (-1, None, Data(b""))
283:         self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)
284:         driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)
285: 
286:     def test_retained_timeout_output_does_not_count_as_fresh_input(self):
287:         driver, _, _, logger, *_ = self.make_driver()
288:         terminal = Terminal(MagicMock(), logger)
289:         terminal._ensure_reader = lambda: None
290:         terminal._read_queue.put(b"partial token")
291:         driver._terminal = terminal
292: 
293:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.001):
294:             state, output, matched = driver._next_state()
295:             self.assertEqual(state, FOSCliState.UNKNOWN)
296:             self.assertEqual(bytes(output), b"partial token")
297:             self.assertFalse(matched)
298:             state, output, matched = driver._next_state()
299:             self.assertEqual(state, FOSCliState.TN_TIMEOUT)
300:             self.assertEqual(bytes(output), b"partial token")
301:             self.assertFalse(matched)
302: 
303:     def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):
304:         driver, terminal, commander, *_ = self.make_driver()
305:         pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]
306:         panic = (
307:             b"Kernel panic - not syncing: VFS: Unable to mount root fs\r\n"
308:             b"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\r\n"
309:         )
310: 
311:         self.assertIsNone(
312:             re.search(
313:                 pattern,
314:                 b"Kernel panic - not syncing: VFS: Unable to mount root fs",
315:             )
316:         )
317:         match = re.search(pattern, panic)
318:         self.assertIsNotNone(match)
319:         terminal.expect.return_value = (
320:             FOSCliState.KERNEL_PANIC.value,
321:             match,
322:             Data(panic),
323:         )
324: 
325:         with self.assertRaisesRegex(KernelPanicError, "Kernel panic detected"):
326:             driver.process_state()
327: 
328:         commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))
329: 
330: 
331: if __name__ == "__main__":
332:     unittest.main()

(End of file - total 332 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3df1b001Jc1IRysAXA6qlz",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3d625001pfFAbj0BYyugan",
  "callID": "call_ba9a54f7be364e66bf9de5b3",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_terminal_driver.py",
      "offset": 1,
      "limit": 600
    },
    "output": "<path>/source/head/fortinet/tests/test_common_terminal_driver.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Serial terminal buffering and FortiOS CLI state-machine tests.\"\"\"\n2: \n3: import logging\n4: import re\n5: import sys\n6: import threading\n7: import unittest\n8: from contextlib import contextmanager\n9: from unittest.mock import MagicMock, patch\n10: \n11: REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n12: sys.path.insert(0, str(REPO_ROOT))\n13: \n14: from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n15: from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n16: from fortinet.common.fos_cli_driver import (  # noqa: E402\n17:     FOSCliDriver,\n18:     KernelPanicError,\n19: )\n20: from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n21: \n22: \n23: class ByteQueueTests(unittest.TestCase):\n24:     def test_put_get_close_timeout_and_failure(self):\n25:         queue = _ByteQueue(3)\n26:         queue.put(b\"abc\")\n27:         self.assertEqual(queue.get_one(), b\"abc\")\n28:         queue.put(b\"def\")\n29:         self.assertEqual(queue.get(), b\"def\")\n30:         self.assertEqual(queue.get(0), b\"\")\n31:         queue.close()\n32:         queue.put(b\"ignored\")\n33:         self.assertEqual(queue.get(), b\"\")\n34:         failed = _ByteQueue(5)\n35:         failed.fail(ValueError(\"read failed\"))\n36:         with self.assertRaisesRegex(ValueError, \"read failed\"):\n37:             failed.get(0)\n38: \n39:     def test_blocked_get_wakes_when_data_arrives(self):\n40:         queue = _ByteQueue(10)\n41:         result = []\n42:         reader = threading.Thread(target=lambda: result.append(queue.get(1)))\n43:         reader.start()\n44:         queue.put(b\"ready\")\n45:         reader.join(1)\n46:         self.assertEqual(result, [b\"ready\"])\n47: \n48: \n49: class TerminalTests(unittest.TestCase):\n50:     def terminal_with_data(self, data, limit=100):\n51:         terminal = Terminal(MagicMock(), MagicMock())\n52:         terminal._buffer_limit = limit\n53:         terminal._read_queue = _ByteQueue(limit)\n54:         terminal._read_queue.put(data)\n55:         terminal._ensure_reader = lambda: None\n56:         return terminal\n57: \n58:     def test_data_wrapper_and_expect_earliest_match_preserves_tail(self):\n59:         view = Data(b\"hello\")\n60:         self.assertTrue(view)\n61:         self.assertEqual(len(view), 5)\n62:         self.assertIn(b\"ell\", view)\n63:         self.assertEqual(view.decode(), \"hello\")\n64:         self.assertTrue(view.startswith(b\"he\"))\n65:         self.assertEqual(view, b\"hello\")\n66:         terminal = self.terminal_with_data(b\"prefix PROMPT trailing\")\n67:         index, match, output = terminal.expect([b\"trailing\", b\"PROMPT\"], timeout=0.1)\n68:         self.assertEqual(index, 1)\n69:         self.assertEqual(match.group(), b\"PROMPT\")\n70:         self.assertEqual(bytes(output), b\"prefix PROMPT\")\n71:         self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n72:         no_match = self.terminal_with_data(b\"abc\")\n73:         result = no_match.expect([b\"never\"], timeout=0)\n74:         self.assertEqual(result[0:2], (-1, None))\n75:         self.assertEqual(bytes(result[2]), b\"\")\n76: \n77:     def test_discard_retained_prefix_and_buffer_limit_error(self):\n78:         terminal = self.terminal_with_data(b\"output prompt\", limit=20)\n79:         _, _, _ = terminal.expect([b\"prompt\"], timeout=0.1)\n80:         data = Data(b\"output\", terminal._discard_prefix)\n81:         terminal._buffer = bytearray(b\"output trailing\")\n82:         data.discard(b\"output\")\n83:         self.assertTrue(data.discarded)\n84:         self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n85:         data.discard(b\"wrong\")\n86:         terminal._buffer = bytearray(b\"123456\")\n87:         terminal._buffer_limit = 5\n88:         with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n89:             terminal._enforce_buffer_limit()\n90:         terminal._logger.error.assert_called_once()\n91: \n92:     def test_timeout_preserves_partial_token_for_a_later_read(self):\n93:         terminal = self.terminal_with_data(b\"Login incor\")\n94:         pattern = rb\"(?m)^Login incorrect\\r?$\"\n95:         index, match, output = terminal.expect([pattern], timeout=0.001)\n96:         self.assertEqual((index, match), (-1, None))\n97:         self.assertEqual(bytes(output), b\"Login incor\")\n98:         # Inspection without discard keeps the partial token, including when\n99:         # another wait expires without receiving any more bytes.\n100:         _, _, output = terminal.expect([pattern], timeout=0)\n101:         self.assertEqual(bytes(output), b\"Login incor\")\n102:         terminal._read_queue.put(b\"rect\\n\")\n103:         index, match, output = terminal.expect([pattern], timeout=0.1)\n104:         self.assertEqual(index, 0)\n105:         self.assertEqual(match.group(), b\"Login incorrect\")\n106:         self.assertEqual(bytes(output), b\"Login incorrect\")\n107:         self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n108: \n109:     def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n110:         terminal = self.terminal_with_data(b\"Verifying pass\")\n111:         _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n112:         self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n113: \n114:         terminal._read_queue.put(b\"word...\\n\")\n115:         _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n116:         self.assertIsNone(match)\n117:         self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n118:         self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n119:         output.discard()\n120:         self.assertEqual(bytes(terminal._buffer), b\"\")\n121: \n122:     def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n123:         prefix = b\"\\nVerifying password...\\n\"\n124:         chunk = b\"admin\\nadmin\\n\"\n125:         terminal = self.terminal_with_data(chunk)\n126:         terminal._buffer.extend(prefix)\n127: \n128:         _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n129:         self.assertEqual(bytes(output), prefix + chunk)\n130:         attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n131:         attempt.on_output(output)\n132: \n133:         self.assertEqual(bytes(attempt.output), prefix + chunk)\n134:         self.assertEqual(bytes(terminal._buffer), b\"\")\n135:         terminal._logger.warning.assert_not_called()\n136: \n137:     def test_suppression_is_nested_and_restores_context(self):\n138:         @contextmanager\n139:         def context():\n140:             events.append(\"enter\")\n141:             try:\n142:                 yield\n143:             finally:\n144:                 events.append(\"exit\")\n145:         events = []\n146:         connection = MagicMock()\n147:         connection.suppress_output.return_value = context()\n148:         terminal = Terminal(connection, MagicMock())\n149:         with terminal.suppress_output():\n150:             with terminal.suppress_output():\n151:                 self.assertEqual(terminal._output_suppression_depth, 2)\n152:         self.assertEqual(events, [\"enter\", \"exit\"])\n153:         self.assertIsNone(terminal._output_suppression_context)\n154: \n155:     def test_write_and_close_flushes_writer(self):\n156:         connection = MagicMock()\n157:         terminal = Terminal(connection, MagicMock())\n158:         terminal.write(\"hello\")\n159:         terminal.write(b\" world\")\n160:         terminal.close()\n161:         written = b\"\".join(call.args[0] for call in connection.write.call_args_list)\n162:         self.assertEqual(written, b\"hello world\")\n163:         connection.close.assert_called_once()\n164: \n165:     def test_reader_failure_propagates_and_terminal_buffer_setting(self):\n166:         reader = MagicMock()\n167:         reader.read_very_eager.side_effect = OSError(\"serial failed\")\n168:         logger = MagicMock()\n169:         terminal = Terminal(reader, logger)\n170:         stop = threading.Event()\n171:         queue = _ByteQueue(10)\n172:         terminal._read_forever(stop, queue)\n173:         with self.assertRaisesRegex(OSError, \"serial failed\"):\n174:             queue.get(0)\n175:         logger.exception.assert_called_once()\n176:         with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n177:             self.assertEqual(terminal_buffer_limit_bytes(), 32)\n178:         with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n179:             self.assertEqual(terminal_buffer_limit_bytes(), 64)\n180:         with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n181:             with self.assertRaises(ValueError):\n182:                 terminal_buffer_limit_bytes()\n183: \n184:     def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n185:         for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n186:             with self.subTest(env_name=env_name):\n187:                 terminal = self.terminal_with_data(b\"matched\")\n188:                 with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n189:                     terminal.expect([b\"matched\"], timeout=0.1)\n190:                 terminal._logger.log.assert_called_once_with(\n191:                     TRACE_LEVEL,\n192:                     \"buffer: bytearray(b'matched')\",\n193:                 )\n194: \n195: \n196: class DriverTests(unittest.TestCase):\n197:     def make_driver(self, *, allow_recovery=False):\n198:         terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n199:         commander.ready = False\n200:         creds = Credentials(\"admin\", \"old\")\n201:         blank = MagicMock()\n202:         bootstrap = MagicMock()\n203:         driver = FOSCliDriver(terminal, commander, creds, logger, \"new\", blank, bootstrap, allow_recovery)\n204:         return driver, terminal, commander, logger, blank, bootstrap\n205: \n206:     def test_prompt_patterns_responses_and_state_callbacks(self):\n207:         driver, terminal, commander, logger, blank, bootstrap = self.make_driver()\n208:         driver.set_prompt_patterns(\"lab[1]\")\n209:         self.assertIsNotNone(re.search(driver.state_patterns[FOSCliState.CMD_PROMPT.value], b\"lab[1] #\"))\n210:         self.assertIsNotNone(re.search(driver.state_patterns[FOSCliState.CMD_PROMPT.value], b\"lab[1] #\\r\"))\n211:         driver._provide_username()\n212:         driver._provide_password()\n213:         driver._provide_current_password()\n214:         driver._provide_new_password()\n215:         driver._confirm_new_password()\n216:         driver._continue_pager()\n217:         self.assertEqual(terminal.write.call_args_list[0].args[0], b\"admin\\r\")\n218:         self.assertEqual(terminal.write.call_args_list[-1].args[0], b\" \")\n219:         self.assertTrue(driver._pending_bootstrap_activation)\n220:         driver._credential_accepted()\n221:         bootstrap.assert_called_once()\n222:         driver._process_state(FOSCliState.CMD_PROMPT_ECHO, Data(b\"hostname # get\"))\n223:         commander.on_prompt_echo.assert_called_once()\n224:         self.assertEqual(commander.on_state.call_count, 0)\n225:         driver._process_state(FOSCliState.CMD_PROMPT, Data(b\"hostname #\"))\n226:         commander.tick.assert_called()\n227:         driver._last_known_state = FOSCliState.CMD_PROMPT\n228:         driver._current_state = FOSCliState.TN_TIMEOUT\n229:         driver._process_state(FOSCliState.TN_TIMEOUT, Data(b\"\"))\n230:         commander.on_idle_prompt.assert_called_once()\n231:         self.assertTrue(driver.at_command_prompt)\n232: \n233:     def test_blank_fallback_and_previous_credential_recovery(self):\n234:         driver, terminal, commander, logger, blank, bootstrap = self.make_driver(allow_recovery=True)\n235:         driver._credential_rejected()\n236:         driver._provide_password()\n237:         blank.assert_called_once()\n238:         self.assertFalse(driver._blank_fallback_available)\n239:         self.assertEqual(terminal.write.call_args.args[0], b\"\\r\")\n240:         driver.remember_current_credentials()\n241:         driver._credential_rejected()\n242:         driver._provide_username()\n243:         driver._provide_password()\n244:         self.assertEqual(terminal.write.call_args_list[-2].args[0], b\"admin\\r\")\n245:         self.assertEqual(terminal.write.call_args_list[-1].args[0], b\"old\\r\")\n246:         driver._credential_accepted()\n247:         commander.record_feature_error.assert_called_once()\n248:         driver._credential_accepted()\n249:         commander.resolve_feature_error.assert_called_once()\n250: \n251:     def test_rejected_and_recovery_credential_branches(self):\n252:         driver, terminal, commander, logger, blank, bootstrap = self.make_driver()\n253:         driver._initial_login_complete = True\n254:         with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n255:             driver._credential_rejected()\n256:         driver._license_failed()\n257:         driver._last_known_state = FOSCliState.REBOOTING\n258:         driver._unknown()\n259:         self.assertEqual(driver._idle_spins, 1)\n260:         driver._unknown_started_at = 0\n261:         with patch(\"fortinet.common.fos_cli_driver.time.monotonic\", side_effect=[31, 32, 64, 65, 96, 97]):\n262:             driver._recover_unknown_stall()\n263:             driver._recover_unknown_stall()\n264:             driver._recover_unknown_stall()\n265:         self.assertEqual(terminal.write.call_count, 3)\n266:         driver._unknown_newlines = 3\n267:         driver._unknown_started_at = 1\n268:         with patch(\"fortinet.common.fos_cli_driver.time.monotonic\", return_value=40):\n269:             with self.assertRaisesRegex(RuntimeError, \"unknown state\"):\n270:                 driver._recover_unknown_stall()\n271:         driver._clear_unknown_stall()\n272:         self.assertIsNone(driver._unknown_started_at)\n273: \n274:     def test_state_selection_and_timeout_processing(self):\n275:         driver, terminal, commander, logger, *_ = self.make_driver()\n276:         terminal.expect.return_value = (FOSCliState.PROVIDE_USERNAME.value, re.search(b\"login\", b\"login\"), Data(b\"login\"))\n277:         state, output, matched = driver._next_state()\n278:         self.assertEqual(state, FOSCliState.PROVIDE_USERNAME)\n279:         self.assertTrue(matched)\n280:         terminal.expect.return_value = (-1, None, Data(b\"noise\"))\n281:         self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n282:         terminal.expect.return_value = (-1, None, Data(b\"\"))\n283:         self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n284:         driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n285: \n286:     def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n287:         driver, _, _, logger, *_ = self.make_driver()\n288:         terminal = Terminal(MagicMock(), logger)\n289:         terminal._ensure_reader = lambda: None\n290:         terminal._read_queue.put(b\"partial token\")\n291:         driver._terminal = terminal\n292: \n293:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n294:             state, output, matched = driver._next_state()\n295:             self.assertEqual(state, FOSCliState.UNKNOWN)\n296:             self.assertEqual(bytes(output), b\"partial token\")\n297:             self.assertFalse(matched)\n298:             state, output, matched = driver._next_state()\n299:             self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n300:             self.assertEqual(bytes(output), b\"partial token\")\n301:             self.assertFalse(matched)\n302: \n303:     def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n304:         driver, terminal, commander, *_ = self.make_driver()\n305:         pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n306:         panic = (\n307:             b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n308:             b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n309:         )\n310: \n311:         self.assertIsNone(\n312:             re.search(\n313:                 pattern,\n314:                 b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n315:             )\n316:         )\n317:         match = re.search(pattern, panic)\n318:         self.assertIsNotNone(match)\n319:         terminal.expect.return_value = (\n320:             FOSCliState.KERNEL_PANIC.value,\n321:             match,\n322:             Data(panic),\n323:         )\n324: \n325:         with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n326:             driver.process_state()\n327: \n328:         commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n329: \n330: \n331: if __name__ == \"__main__\":\n332:     unittest.main()\n\n(End of file - total 332 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_terminal_driver.py",
    "metadata": {
      "preview": "\"\"\"Serial terminal buffering and FortiOS CLI state-machine tests.\"\"\"\n\nimport logging\nimport re\nimport sys\nimport threading\nimport unittest\nfrom contextlib import contextmanager\nfrom unittest.mock import MagicMock, patch\n\nREPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\nfrom fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\nfrom fortinet.common.fos_cli_driver import (  # noqa: E402\n    FOSCliDriver,\n    KernelPanicError,\n)\nfrom fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_terminal_driver.py",
        "text": "\"\"\"Serial terminal buffering and FortiOS CLI state-machine tests.\"\"\"\n\nimport logging\nimport re\nimport sys\nimport threading\nimport unittest\nfrom contextlib import contextmanager\nfrom unittest.mock import MagicMock, patch\n\nREPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\nfrom fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\nfrom fortinet.common.fos_cli_driver import (  # noqa: E402\n    FOSCliDriver,\n    KernelPanicError,\n)\nfrom fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n\n\nclass ByteQueueTests(unittest.TestCase):\n    def test_put_get_close_timeout_and_failure(self):\n        queue = _ByteQueue(3)\n        queue.put(b\"abc\")\n        self.assertEqual(queue.get_one(), b\"abc\")\n        queue.put(b\"def\")\n        self.assertEqual(queue.get(), b\"def\")\n        self.assertEqual(queue.get(0), b\"\")\n        queue.close()\n        queue.put(b\"ignored\")\n        self.assertEqual(queue.get(), b\"\")\n        failed = _ByteQueue(5)\n        failed.fail(ValueError(\"read failed\"))\n        with self.assertRaisesRegex(ValueError, \"read failed\"):\n            failed.get(0)\n\n    def test_blocked_get_wakes_when_data_arrives(self):\n        queue = _ByteQueue(10)\n        result = []\n        reader = threading.Thread(target=lambda: result.append(queue.get(1)))\n        reader.start()\n        queue.put(b\"ready\")\n        reader.join(1)\n        self.assertEqual(result, [b\"ready\"])\n\n\nclass TerminalTests(unittest.TestCase):\n    def terminal_with_data(self, data, limit=100):\n        terminal = Terminal(MagicMock(), MagicMock())\n        terminal._buffer_limit = limit\n        terminal._read_queue = _ByteQueue(limit)\n        terminal._read_queue.put(data)\n        terminal._ensure_reader = lambda: None\n        return terminal\n\n    def test_data_wrapper_and_expect_earliest_match_preserves_tail(self):\n        view = Data(b\"hello\")\n        self.assertTrue(view)\n        self.assertEqual(len(view), 5)\n        self.assertIn(b\"ell\", view)\n        self.assertEqual(view.decode(), \"hello\")\n        self.assertTrue(view.startswith(b\"he\"))\n        self.assertEqual(view, b\"hello\")\n        terminal = self.terminal_with_data(b\"prefix PROMPT trailing\")\n        index, match, output = terminal.expect([b\"trailing\", b\"PROMPT\"], timeout=0.1)\n        self.assertEqual(index, 1)\n        self.assertEqual(match.group(), b\"PROMPT\")\n        self.assertEqual(bytes(output), b\"prefix PROMPT\")\n        self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n        no_match = self.terminal_with_data(b\"abc\")\n        result = no_match.expect([b\"never\"], timeout=0)\n        self.assertEqual(result[0:2], (-1, None))\n        self.assertEqual(bytes(result[2]), b\"\")\n\n    def test_discard_retained_prefix_and_buffer_limit_error(self):\n        terminal = self.terminal_with_data(b\"output prompt\", limit=20)\n        _, _, _ = terminal.expect([b\"prompt\"], timeout=0.1)\n        data = Data(b\"output\", terminal._discard_prefix)\n        terminal._buffer = bytearray(b\"output trailing\")\n        data.discard(b\"output\")\n        self.assertTrue(data.discarded)\n        self.assertEqual(bytes(terminal._buffer), b\" trailing\")\n        data.discard(b\"wrong\")\n        terminal._buffer = bytearray(b\"123456\")\n        terminal._buffer_limit = 5\n        with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n            terminal._enforce_buffer_limit()\n        terminal._logger.error.assert_called_once()\n\n    def test_timeout_preserves_partial_token_for_a_later_read(self):\n        terminal = self.terminal_with_data(b\"Login incor\")\n        pattern = rb\"(?m)^Login incorrect\\r?$\"\n        index, match, output = terminal.expect([pattern], timeout=0.001)\n        self.assertEqual((index, match), (-1, None))\n        self.assertEqual(bytes(output), b\"Login incor\")\n        # Inspection without discard keeps the partial token, including when\n        # another wait expires without receiving any more bytes.\n        _, _, output = terminal.expect([pattern], timeout=0)\n        self.assertEqual(bytes(output), b\"Login incor\")\n        terminal._read_queue.put(b\"rect\\n\")\n        index, match, output = terminal.expect([pattern], timeout=0.1)\n        self.assertEqual(index, 0)\n        self.assertEqual(match.group(), b\"Login incorrect\")\n        self.assertEqual(bytes(output), b\"Login incorrect\")\n        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n\n    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n        terminal = self.terminal_with_data(b\"Verifying pass\")\n        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n\n        terminal._read_queue.put(b\"word...\\n\")\n        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n        self.assertIsNone(match)\n        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n        output.discard()\n        self.assertEqual(bytes(terminal._buffer), b\"\")\n\n    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n        prefix = b\"\\nVerifying password...\\n\"\n        chunk = b\"admin\\nadmin\\n\"\n        terminal = self.terminal_with_data(chunk)\n        terminal._buffer.extend(prefix)\n\n        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n        self.assertEqual(bytes(output), prefix + chunk)\n        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n        attempt.on_output(output)\n\n        self.assertEqual(bytes(attempt.output), prefix + chunk)\n        self.assertEqual(bytes(terminal._buffer), b\"\")\n        terminal._logger.warning.assert_not_called()\n\n    def test_suppression_is_nested_and_restores_context(self):\n        @contextmanager\n        def context():\n            events.append(\"enter\")\n            try:\n                yield\n            finally:\n                events.append(\"exit\")\n        events = []\n        connection = MagicMock()\n        connection.suppress_output.return_value = context()\n        terminal = Terminal(connection, MagicMock())\n        with terminal.suppress_output():\n            with terminal.suppress_output():\n                self.assertEqual(terminal._output_suppression_depth, 2)\n        self.assertEqual(events, [\"enter\", \"exit\"])\n        self.assertIsNone(terminal._output_suppression_context)\n\n    def test_write_and_close_flushes_writer(self):\n        connection = MagicMock()\n        terminal = Terminal(connection, MagicMock())\n        terminal.write(\"hello\")\n        terminal.write(b\" world\")\n        terminal.close()\n        written = b\"\".join(call.args[0] for call in connection.write.call_args_list)\n        self.assertEqual(written, b\"hello world\")\n        connection.close.assert_called_once()\n\n    def test_reader_failure_propagates_and_terminal_buffer_setting(self):\n        reader = MagicMock()\n        reader.read_very_eager.side_effect = OSError(\"serial failed\")\n        logger = MagicMock()\n        terminal = Terminal(reader, logger)\n        stop = threading.Event()\n        queue = _ByteQueue(10)\n        terminal._read_forever(stop, queue)\n        with self.assertRaisesRegex(OSError, \"serial failed\"):\n            queue.get(0)\n        logger.exception.assert_called_once()\n        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n            self.assertEqual(terminal_buffer_limit_bytes(), 32)\n        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n            with self.assertRaises(ValueError):\n                terminal_buffer_limit_bytes()\n\n    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n            with self.subTest(env_name=env_name):\n                terminal = self.terminal_with_data(b\"matched\")\n                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n                    terminal.expect([b\"matched\"], timeout=0.1)\n                terminal._logger.log.assert_called_once_with(\n                    TRACE_LEVEL,\n                    \"buffer: bytearray(b'matched')\",\n                )\n\n\nclass DriverTests(unittest.TestCase):\n    def make_driver(self, *, allow_recovery=False):\n        terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n        commander.ready = False\n        creds = Credentials(\"admin\", \"old\")\n        blank = MagicMock()\n        bootstrap = MagicMock()\n        driver = FOSCliDriver(terminal, commander, creds, logger, \"new\", blank, bootstrap, allow_recovery)\n        return driver, terminal, commander, logger, blank, bootstrap\n\n    def test_prompt_patterns_responses_and_state_callbacks(self):\n        driver, terminal, commander, logger, blank, bootstrap = self.make_driver()\n        driver.set_prompt_patterns(\"lab[1]\")\n        self.assertIsNotNone(re.search(driver.state_patterns[FOSCliState.CMD_PROMPT.value], b\"lab[1] #\"))\n        self.assertIsNotNone(re.search(driver.state_patterns[FOSCliState.CMD_PROMPT.value], b\"lab[1] #\\r\"))\n        driver._provide_username()\n        driver._provide_password()\n        driver._provide_current_password()\n        driver._provide_new_password()\n        driver._confirm_new_password()\n        driver._continue_pager()\n        self.assertEqual(terminal.write.call_args_list[0].args[0], b\"admin\\r\")\n        self.assertEqual(terminal.write.call_args_list[-1].args[0], b\" \")\n        self.assertTrue(driver._pending_bootstrap_activation)\n        driver._credential_accepted()\n        bootstrap.assert_called_once()\n        driver._process_state(FOSCliState.CMD_PROMPT_ECHO, Data(b\"hostname # get\"))\n        commander.on_prompt_echo.assert_called_once()\n        self.assertEqual(commander.on_state.call_count, 0)\n        driver._process_state(FOSCliState.CMD_PROMPT, Data(b\"hostname #\"))\n        commander.tick.assert_called()\n        driver._last_known_state = FOSCliState.CMD_PROMPT\n        driver._current_state = FOSCliState.TN_TIMEOUT\n        driver._process_state(FOSCliState.TN_TIMEOUT, Data(b\"\"))\n        commander.on_idle_prompt.assert_called_once()\n        self.assertTrue(driver.at_command_prompt)\n\n    def test_blank_fallback_and_previous_credential_recovery(self):\n        driver, terminal, commander, logger, blank, bootstrap = self.make_driver(allow_recovery=True)\n        driver._credential_rejected()\n        driver._provide_password()\n        blank.assert_called_once()\n        self.assertFalse(driver._blank_fallback_available)\n        self.assertEqual(terminal.write.call_args.args[0], b\"\\r\")\n        driver.remember_current_credentials()\n        driver._credential_rejected()\n        driver._provide_username()\n        driver._provide_password()\n        self.assertEqual(terminal.write.call_args_list[-2].args[0], b\"admin\\r\")\n        self.assertEqual(terminal.write.call_args_list[-1].args[0], b\"old\\r\")\n        driver._credential_accepted()\n        commander.record_feature_error.assert_called_once()\n        driver._credential_accepted()\n        commander.resolve_feature_error.assert_called_once()\n\n    def test_rejected_and_recovery_credential_branches(self):\n        driver, terminal, commander, logger, blank, bootstrap = self.make_driver()\n        driver._initial_login_complete = True\n        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n            driver._credential_rejected()\n        driver._license_failed()\n        driver._last_known_state = FOSCliState.REBOOTING\n        driver._unknown()\n        self.assertEqual(driver._idle_spins, 1)\n        driver._unknown_started_at = 0\n        with patch(\"fortinet.common.fos_cli_driver.time.monotonic\", side_effect=[31, 32, 64, 65, 96, 97]):\n            driver._recover_unknown_stall()\n            driver._recover_unknown_stall()\n            driver._recover_unknown_stall()\n        self.assertEqual(terminal.write.call_count, 3)\n        driver._unknown_newlines = 3\n        driver._unknown_started_at = 1\n        with patch(\"fortinet.common.fos_cli_driver.time.monotonic\", return_value=40):\n            with self.assertRaisesRegex(RuntimeError, \"unknown state\"):\n                driver._recover_unknown_stall()\n        driver._clear_unknown_stall()\n        self.assertIsNone(driver._unknown_started_at)\n\n    def test_state_selection_and_timeout_processing(self):\n        driver, terminal, commander, logger, *_ = self.make_driver()\n        terminal.expect.return_value = (FOSCliState.PROVIDE_USERNAME.value, re.search(b\"login\", b\"login\"), Data(b\"login\"))\n        state, output, matched = driver._next_state()\n        self.assertEqual(state, FOSCliState.PROVIDE_USERNAME)\n        self.assertTrue(matched)\n        terminal.expect.return_value = (-1, None, Data(b\"noise\"))\n        self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n        terminal.expect.return_value = (-1, None, Data(b\"\"))\n        self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n        driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n\n    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n        driver, _, _, logger, *_ = self.make_driver()\n        terminal = Terminal(MagicMock(), logger)\n        terminal._ensure_reader = lambda: None\n        terminal._read_queue.put(b\"partial token\")\n        driver._terminal = terminal\n\n        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n            state, output, matched = driver._next_state()\n            self.assertEqual(state, FOSCliState.UNKNOWN)\n            self.assertEqual(bytes(output), b\"partial token\")\n            self.assertFalse(matched)\n            state, output, matched = driver._next_state()\n            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n            self.assertEqual(bytes(output), b\"partial token\")\n            self.assertFalse(matched)\n\n    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n        driver, terminal, commander, *_ = self.make_driver()\n        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n        panic = (\n            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n        )\n\n        self.assertIsNone(\n            re.search(\n                pattern,\n                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n            )\n        )\n        match = re.search(pattern, panic)\n        self.assertIsNotNone(match)\n        terminal.expect.return_value = (\n            FOSCliState.KERNEL_PANIC.value,\n            match,\n            Data(panic),\n        )\n\n        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n            driver.process_state()\n\n        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 332,
        "totalLines": 332,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716379422,
      "end": 1793716379426
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_commander.py",
  "offset": 1,
  "limit": 700
}

Output

<path>/source/head/fortinet/common/fos_commander.py</path>
<type>file</type>
<content>
1: """Event-driven command scheduler for the FortiOS CLI."""
2: 
3: import datetime
4: import re
5: from collections import deque
6: from contextlib import ExitStack
7: from dataclasses import dataclass
8: 
9: from .cli_commands import (
10:     CleanupAction,
11:     CommandAttempt,
12:     CommandSequence,
13:     CommandSpec,
14:     ConfigBlock,
15:     ContextLossAction,
16:     SessionLossAction,
17:     flatten_commands,
18: )
19: from .terminal import Data
20: from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL
21: 
22: DISPATCHABLE_COMPLETION_STATES = {
23:     FOSCliState.CMD_PROMPT,
24:     FOSCliState.CONFIRMATION,
25:     FOSCliState.MULTILINE_PROMPT,
26: }
27: COMMAND_FAILURE_PATTERN = re.compile(
28:     rb"(?mi)^\s*Command fail\.\s*Return code\s+(-?\d+)"
29: )
30: CLI_PROMPT_CONTEXT_PATTERN = re.compile(
31:     rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX
32:     + rb"(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$"
33: )
34: 
35: 
36: @dataclass
37: class _StandardOutputContext:
38:     feature: object
39:     callback: object
40:     phase: str = "inspect"
41:     restore: bool = False
42: 
43: 
44: class FOSCommander:
45:     MAX_COMMAND_RECOVERY_RETRIES = 1
46:     _CONSOLE_OUTPUT_PATTERN = re.compile(rb"(?mi)^\s*set output (more|standard)\s*\r?$")
47:     _CONSOLE_INSPECT_LINE = "show full-configuration system console"
48:     _CONSOLE_STANDARD_LINE = "set output standard"
49: 
50:     def __init__(self, terminal, logger, continue_on_error=False):
51:         self.terminal = terminal
52:         self.logger = logger
53:         self._features = deque()
54:         self._active_feature = None
55:         self._active_commands = ()
56:         self._pending = deque()
57:         self._inflight = None
58:         self._attempt_number = 0
59:         self._session_epoch = 0
60:         self._recovering = False
61:         self._cleanup = deque()
62:         self._cleanup_actions = {}
63:         self._in_cleanup = False
64:         self._standard_output_context = None
65:         self._suppression = ExitStack()
66:         self._ready = False
67:         self._startup_complete = False
68:         self._feature_errors = []
69:         self._authenticated_once = False
70:         self._completed_messages = deque()
71:         self._start_time = datetime.datetime.now()
72:         self._continue_on_error = continue_on_error
73:         self._pending_feature_error = None
74:         self._current_state = None
75:         self._callback_failed = False
76:         self._prompt_context = None
77:         self._block_prompt_context = None
78:         self._recovery_retries = {}
79:         self._cleanup_retries = {}
80:         self._replay_context_target = None
81:         self._context_reset_attempted = False
82:         self._in_context_reset = False
83: 
84:     def _call_feature(self, callback, *args):
85:         """Run a feature callback and apply best-effort policy at this boundary."""
86:         try:
87:             return callback(*args)
88:         except Exception as error:
89:             self._handle_work_error(error, from_callback=True)
90:             return None
91: 
92:     def _handle_work_error(self, error, *, from_callback=False):
93:         """Apply the configured failure policy after feature/recovery decisions."""
94:         if not self._continue_on_error:
95:             raise error
96:         if from_callback:
97:             self.logger.exception("Bootstrap feature callback failed")
98:         else:
99:             self.logger.error("Bootstrap work failed: %s", error, exc_info=error)
100:         self._pending_feature_error = error
101:         self._callback_failed = True
102: 
103:     def _recover_feature_error(self, *, at_idle_prompt=False):
104:         error = self._pending_feature_error
105:         if error is None or (
106:             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
107:         ):
108:             return False
109:         failed_work = self.continue_after_error(error, at_command_prompt=True)
110:         if failed_work is None:
111:             return False
112:         self._pending_feature_error = None
113:         self.logger.error(
114:             "Bootstrap work %s failed; continuing with remaining features "
115:             "because FOS_EXIT_ON_BOOTSTRAP_ERROR=false",
116:             failed_work,
117:         )
118:         self._dispatch_next()
119:         return True
120: 
121:     @property
122:     def ready(self):
123:         return self._ready
124: 
125:     @property
126:     def busy(self):
127:         return self._inflight is not None or bool(self._pending) or bool(self._cleanup)
128: 
129:     @property
130:     def startup_complete(self):
131:         """Whether the initial feature queue has drained, with or without errors."""
132:         return self._startup_complete
133: 
134:     @property
135:     def feature_errors(self):
136:         """Bootstrap feature errors recorded while best-effort mode is active."""
137:         return tuple(self._feature_errors)
138: 
139:     def continue_after_error(self, error, at_command_prompt):
140:         """Skip failed work only when the CLI is back at a usable prompt.
141: 
142:         A login rejection after the driver's credential recovery attempts, or
143:         an error during an interactive prompt, cannot be recovered by sending
144:         the next feature's commands, so automatic bootstrap must stop.
145:         """
146:         if not at_command_prompt or self._ready:
147:             return None
148:         if self._active_feature is None and not self._in_cleanup:
149:             return None
150: 
151:         if self._active_feature is not None:
152:             failed_name = self._active_feature.name
153:             self._pending.clear()
154:             self._active_commands = ()
155:             self._inflight = None
156:             self._suppression.close()
157:             self._suppression = ExitStack()
158:             self._finish_standard_output_context(self._active_feature)
159:             self._schedule_feature_cleanup(self._active_feature, "interruption")
160:             self._active_feature = None
161:         else:
162:             failed_name = "cleanup"
163:             self._inflight = None
164:             self._suppression.close()
165:             self._suppression = ExitStack()
166: 
167:         self._in_cleanup = False
168:         self._replay_context_target = None
169:         self._in_context_reset = False
170:         self._cleanup_retries.clear()
171:         self._feature_errors.append((failed_name, str(error)))
172:         return failed_name
173: 
174:     def record_feature_error(self, name, error):
175:         """Record a recoverable bootstrap problem without stopping the queue."""
176:         self._feature_errors.append((name, str(error)))
177:         self.logger.info("Using recovery for %s: %s", name, error)
178: 
179:     def resolve_feature_error(self, name, resolution):
180:         """Clear a recoverable feature error after its condition is resolved."""
181:         remaining = [
182:             (feature_name, error)
183:             for feature_name, error in self._feature_errors
184:             if feature_name != name
185:         ]
186:         resolved_count = len(self._feature_errors) - len(remaining)
187:         if resolved_count:
188:             self._feature_errors = remaining
189:             self.logger.info(
190:                 "Resolved %s bootstrap recovery after %s",
191:                 name,
192:                 resolution,
193:             )
194: 
195:     def start(self, features):
196:         self._features.extend(features)
197: 
198:     def tick(self):
199:         if self._pending_feature_error is not None:
200:             return
201:         if self._active_feature and hasattr(self._active_feature, "tick"):
202:             self._call_feature(self._active_feature.tick)
203: 
204:     def submit_block(self, feature, block):
205:         if feature is not self._active_feature:
206:             raise RuntimeError("Inactive feature attempted to submit commands")
207:         if self.busy:
208:             raise RuntimeError("Cannot replace an active command block")
209:         commands = tuple(flatten_commands(block))
210:         self._active_commands = commands
211:         self._pending = deque(commands)
212:         self._block_prompt_context = self._prompt_context
213:         self._recovery_retries = {}
214:         self._replay_context_target = None
215:         self._context_reset_attempted = False
216: 
217:     def feature_complete(self, feature):
218:         if feature is not self._active_feature:
219:             return
220:         if self.busy:
221:             raise RuntimeError("Feature completed while commands are still pending")
222:         feature.mark_completed()
223:         if feature.completion_message:
224:             self._completed_messages.append(feature.completion_message)
225:         self._finish_standard_output_context(feature)
226:         self._schedule_feature_cleanup(feature, "completion")
227:         self._active_feature = None
228:         self._active_commands = ()
229:         if not self._cleanup:
230:             self._activate_next_feature()
231: 
232:     def register_cleanup(self, feature, action):
233:         if not isinstance(action, CleanupAction):
234:             raise TypeError("cleanup must be a CleanupAction")
235:         self._cleanup_actions.setdefault(feature, []).append(action)
236: 
237:     def with_standard_output(self, feature, callback):
238:         """Run a feature callback after standard console output is available."""
239:         if feature is not self._active_feature:
240:             raise RuntimeError("Inactive feature requested standard console output")
241:         if self.busy or self._standard_output_context:
242:             raise RuntimeError("Cannot start a standard console output context while busy")
243:         self._standard_output_context = _StandardOutputContext(feature, callback)
244:         self.submit_block(feature, CommandSequence("console-output-inspect", [
245:             CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),
246:         ]))
247: 
248:     def _schedule_feature_cleanup(self, feature, trigger):
249:         actions = self._cleanup_actions.pop(feature, [])
250:         for action in actions:
251:             if (trigger == "completion" and action.on_completion) or (
252:                 trigger == "interruption" and action.on_interruption
253:             ):
254:                 self.logger.debug(f"Scheduling cleanup {action.name} after {trigger}")
255:                 self._cleanup.extend(action.block.flatten())
256: 
257:     def on_output(self, output):
258:         if not isinstance(output, Data):
259:             raise TypeError("commander output must be terminal.Data")
260:         if not output:
261:             return output
262:         if self._inflight:
263:             if self._call_feature(self._inflight.on_output, output):
264:                 return output
265:             if self._active_feature and self._call_feature(self._active_feature.on_output, output):
266:                 return output
267:         self._inspect_output(output)
268:         return output
269: 
270:     def on_state(self, state, output):
271:         """Called by the driver for every recognized serial state."""
272:         self._current_state = state
273:         self._callback_failed = False
274:         if state == FOSCliState.CMD_PROMPT:
275:             context = self._extract_prompt_context(output)
276:             if context is not None:
277:                 self._prompt_context = context
278:             # Some releases return directly to a usable prompt after login,
279:             # without a Welcome banner. The prompt also ends session recovery.
280:             self._authenticated_once = True
281:             self._recovering = False
282:         if self._pending_feature_error is not None:
283:             if state == FOSCliState.CMD_PROMPT:
284:                 self._recover_feature_error()
285:             elif state == FOSCliState.SESSION_LOST:
286:                 self._session_epoch += 1
287:                 self._recovering = True
288:             elif state == FOSCliState.CREDENTIAL_ACCEPTED:
289:                 self._authenticated_once = True
290:                 self._recovering = False
291:             return
292:         self.on_output(output)
293:         if self._callback_failed:
294:             if state == FOSCliState.CMD_PROMPT:
295:                 self._recover_feature_error()
296:             return
297:         if self._pending_feature_error is not None:
298:             if state == FOSCliState.CMD_PROMPT:
299:                 self._recover_feature_error()
300:             return
301: 
302:         if state == FOSCliState.SESSION_LOST:
303:             self._handle_session_loss()
304:             return
305:         if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:
306:             # Password updates can return to login without the explicit
307:             # SESSION_LOST banner. Requeue the active command block so it is
308:             # applied after the driver restores an accepted login.
309:             self._handle_session_loss()
310:             return
311:         if state == FOSCliState.CREDENTIAL_ACCEPTED:
312:             self._authenticated_once = True
313:             self._recovering = False
314:             return
315:         if self._inflight and state in (
316:             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
317:         ):
318:             self._complete_inflight(state)
319:             return
320: 
321:         if state == FOSCliState.CMD_PROMPT and not self._recovering:
322:             self._dispatch_next()
323:         if self._callback_failed and state == FOSCliState.CMD_PROMPT:
324:             self._recover_feature_error()
325: 
326:     def on_prompt_echo(self, output):
327:         """Handle a prompt line that had trailing text after the prompt token."""
328:         if self.on_output(output).discarded:
329:             return
330:         self.logger.debug("Prompt had unexpected trailing output; requesting a clean prompt")
331:         self.terminal.write(b"\r")
332: 
333:     def _inspect_output(self, output):
334:         if self._recovering:
335:             output.discard()
336: 
337:     def on_idle_prompt(self):
338:         """Recover errors or dispatch work while idle at a known prompt."""
339:         if self._inflight or self._recovering:
340:             return
341:         if self._pending_feature_error is not None:
342:             # The driver calls this after a read timeout at a known CLI prompt.
343:             # on_state has since recorded TN_TIMEOUT, so recover explicitly.
344:             self._recover_feature_error(at_idle_prompt=True)
345:             return
346:         if self._pending or self._cleanup or self._active_feature is None:
347:             self._dispatch_next()
348: 
349:     def _activate_next_feature(self):
350:         if self._ready or self._active_feature or self._recovering:
351:             return
352:         if not self._features:
353:             if self._cleanup:
354:                 return
355:             self._ready = True
356:             self.terminal.close()
357:             if not self._startup_complete:
358:                 self._startup_complete = True
359:                 elapsed = datetime.datetime.now() - self._start_time
360:                 if self._feature_errors:
361:                     failed = ", ".join(name for name, _error in self._feature_errors)
362:                     self.logger.error(
363:                         "Bootstrap reached the end with %d feature error(s) in %s; "
364:                         "failed work: %s",
365:                         len(self._feature_errors),
366:                         elapsed,
367:                         failed,
368:                     )
369:                 else:
370:                     self.logger.info(f"Startup complete in {elapsed}")
371:             else:
372:                 while self._completed_messages:
373:                     self.logger.info(self._completed_messages.popleft())
374:             return
375:         self._active_feature = self._features.popleft()
376:         self.logger.info(f"Activating feature {self._active_feature.name}")
377:         self._call_feature(self._active_feature.begin_activation)
378:         if self._pending_feature_error is None:
379:             self._call_feature(self._active_feature.activate)
380: 
381:     def _dispatch_next(self):
382:         if self._inflight or self._recovering or self._pending_feature_error is not None:
383:             return
384:         if not self._restore_replay_context():
385:             return
386:         if not self._cleanup and self._active_feature is None:
387:             self._activate_next_feature()
388:             if self._active_feature is None:
389:                 return
390:         if self._cleanup:
391:             spec = self._cleanup.popleft()
392:             self._in_cleanup = True
393:             block_index = None
394:         elif not self._pending:
395:             self._call_feature(self._active_feature.on_block_complete)
396:             return
397:         else:
398:             spec = self._pending.popleft()
399:             self._in_cleanup = False
400:             block_index = len(self._active_commands) - len(self._pending) - 1
401:         self._dispatch_command(spec, block_index)
402: 
403:     def _dispatch_command(self, spec, block_index=None):
404:         self._attempt_number += 1
405:         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)
406:         self._inflight.prompt_context_before = self._prompt_context
407:         self._inflight.block_index = block_index
408:         self._inflight.retry_count = (
409:             self._cleanup_retries.get(id(spec), 0)
410:             if self._in_cleanup else self._recovery_retries.get(block_index, 0)
411:         )
412:         if self._active_feature and not self._in_context_reset:
413:             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)
414:             if self._pending_feature_error is not None:
415:                 return
416:         if spec.suppress_output:
417:             self._suppression.enter_context(self.terminal.suppress_output())
418:         self.logger.log(
419:             TRACE_LEVEL,
420:             f"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/"
421:             f"{spec.line!r}"
422:         )
423:         self.terminal.write(f"{spec.line}\r")
424: 
425:     def _complete_inflight(self, state):
426:         attempt = self._inflight
427:         self._inflight = None
428:         self._suppression.close()
429:         self._suppression = ExitStack()
430:         attempt.prompt_context_after = self._prompt_context
431:         if self._in_context_reset:
432:             self._in_context_reset = False
433:             self._dispatch_next()
434:             return
435:         if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
436:             self._handle_context_loss(attempt)
437:             if self._pending_feature_error is not None:
438:                 self._recover_feature_error()
439:             else:
440:                 self._dispatch_next()
441:             return
442:         try:
443:             self._validate_completion(attempt, state)
444:         except RuntimeError as error:
445:             if state != FOSCliState.CMD_PROMPT:
446:                 # An interactive prompt cannot safely advance to another feature.
447:                 raise
448:             self._handle_work_error(error)
449:             if self._pending_feature_error is not None:
450:                 self._recover_feature_error()
451:             return
452:         if self._in_cleanup:
453:             self._cleanup_retries.pop(id(attempt.spec), None)
454:             self._in_cleanup = False
455:             self._dispatch_next()
456:             return
457:         if self._is_standard_output_command(attempt.spec):
458:             self._complete_standard_output_command(attempt)
459:             if self._pending_feature_error is not None:
460:                 return
461:             if not self._recovering:
462:                 self._dispatch_next()
463:             return
464:         completed_feature = self._active_feature
465:         self._call_feature(completed_feature.on_command_executed, attempt, state)
466:         if self._pending_feature_error is not None:
467:             return
468:         # The callback may have installed another block (confirmation/query path).
469:         if not self.busy and self._active_feature is completed_feature:
470:             self._call_feature(completed_feature.on_block_complete)
471:         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:
472:             self._dispatch_next()
473: 
474:     @staticmethod
475:     def _validate_completion(attempt, state):
476:         if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (
477:             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))
478:         ):
479:             raise RuntimeError(
480:                 f"FortiOS command {attempt.spec.line!r} failed "
481:                 f"(return code {failure.group(1).decode()})"
482:             )
483:         expected = attempt.spec.expected_completion_state
484:         if expected is not None and state != expected:
485:             raise RuntimeError(
486:                 "CLI command completed at unexpected prompt: "
487:                 f"expected {expected.name}, received {state.name}"
488:             )
489: 
490:     def _prompt_context_changed(self, attempt):
491:         before = attempt.prompt_context_before
492:         after = attempt.prompt_context_after
493:         return (
494:             before is not None
495:             and after is not None
496:             and before != after
497:             and not self._command_may_change_context(attempt.spec)
498:         )
499: 
500:     def _handle_context_loss(self, attempt):
501:         reason = (
502:             "CLI context changed from "
503:             f"{self._format_prompt_context(attempt.prompt_context_before)} to "
504:             f"{self._format_prompt_context(attempt.prompt_context_after)}"
505:         )
506:         if self._in_cleanup:
507:             self._handle_work_error(RuntimeError(
508:                 f"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay"
509:             ))
510:             return
511:         action = self._call_feature(self._active_feature.on_context_loss, attempt)
512:         if self._pending_feature_error is not None:
513:             return
514:         if action == ContextLossAction.RESTART_BLOCK:
515:             self._restart_active_block(attempt, reason)
516:         elif action == ContextLossAction.FAIL:
517:             self._handle_work_error(RuntimeError(
518:                 f"{reason} during {attempt.spec.line!r}; feature declined replay"
519:             ))
520:         else:
521:             self._handle_work_error(ValueError(f"Unsupported context-loss action: {action!r}"))
522: 
523:     def _restore_replay_context(self):
524:         """Unwind a surviving partial scope once before replaying its openers."""
525:         target = self._replay_context_target
526:         if target is None:
527:             return True
528:         if self._prompt_context == target:
529:             self._replay_context_target = None
530:             return True
531:         if self._context_reset_attempted:
532:             self._handle_work_error(RuntimeError(
533:                 "Unable to restore CLI context before replay: expected "
534:                 f"{self._format_prompt_context(target)}, received "
535:                 f"{self._format_prompt_context(self._prompt_context or ())}"
536:             ))
537:             if self._pending_feature_error is not None:
538:                 self._recover_feature_error()
539:             return False
540:         self._context_reset_attempted = True
541:         self._in_context_reset = True
542:         self._dispatch_command(CommandSpec("abort", suppress_output=True))
543:         return False
544: 
545:     @staticmethod
546:     def _command_may_change_context(spec):
547:         if spec.continuation:
548:             return False
549:         command = spec.line.strip().lower()
550:         return (
551:             command.startswith(("config ", "edit "))
552:             or command in {"next", "end", "abort", "exit", "quit"}
553:             or command == "set vdom-mode multi-vdom"
554:         )
555: 
556:     @staticmethod
557:     def _extract_prompt_context(output):
558:         data = bytes(output)
559:         matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))
560:         if not matches:
561:             return None
562:         return tuple(
563:             item.decode(errors="replace")
564:             for item in re.findall(rb"\(([^)]*)\)", matches[-1].group("context"))
565:         )
566: 
567:     @staticmethod
568:     def _format_prompt_context(context):
569:         return " ".join(f"({item})" for item in context) or "<top-level>"
570: 
571:     def _is_standard_output_command(self, spec):
572:         context = self._standard_output_context
573:         return context is not None and (
574:             spec.line == self._CONSOLE_INSPECT_LINE
575:             or (context.phase == "set-standard" and not self._pending)
576:         )
577: 
578:     def _complete_standard_output_command(self, attempt):
579:         context = self._standard_output_context
580:         if attempt.spec.line == self._CONSOLE_INSPECT_LINE:
581:             match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))
582:             if not match or match.group(1) == b"standard":
583:                 if not match:
584:                     self.logger.warning("Could not determine console output mode; assuming standard output")
585:                 self._start_standard_output_callback(context)
586:                 return
587:             context.phase = "set-standard"
588:             self.submit_block(context.feature, ConfigBlock("system console", [
589:                 self._CONSOLE_STANDARD_LINE,
590:             ]))
591:             return
592:         if context.phase == "set-standard":
593:             context.restore = True
594:             self._start_standard_output_callback(context)
595: 
596:     def _start_standard_output_callback(self, context):
597:         context.phase = "active"
598:         self._call_feature(context.callback)
599: 
600:     def _finish_standard_output_context(self, feature):
601:         context = self._standard_output_context
602:         if context is None or context.feature is not feature:
603:             return
604:         self._standard_output_context = None
605:         if context.restore:
606:             self._cleanup.extend(ConfigBlock("system console", [
607:                 "set output more",
608:             ]).flatten())
609: 
610:     def _handle_session_loss(self):
611:         self._session_epoch += 1
612:         self._recovering = True
613:         if not self._inflight:
614:             return
615:         attempt = self._inflight
616:         self._inflight = None
617:         self._suppression.close()
618:         self._suppression = ExitStack()
619:         if self._in_context_reset:
620:             # Login may itself restore the target scope. The pending replay
621:             # stays bounded by the original command's recovery allowance.
622:             self._in_context_reset = False
623:             return
624:         if self._in_cleanup:
625:             retries = self._cleanup_retries.get(id(attempt.spec), 0)
626:             if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
627:                 self._handle_work_error(RuntimeError(
628:                     f"Session lost repeatedly during cleanup {attempt.spec.line!r}; "
629:                     "retry limit reached"
630:                 ))
631:                 return
632:             self._cleanup_retries[id(attempt.spec)] = retries + 1
633:             self._cleanup.appendleft(attempt.spec)
634:             self._in_cleanup = False
635:             return
636:         self._schedule_feature_cleanup(self._active_feature, "interruption")
637:         action = self._call_feature(
638:             self._active_feature.on_session_loss,
639:             attempt,
640:         )
641:         if self._pending_feature_error is not None:
642:             return
643:         self.logger.info(
644:             f"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}"
645:         )
646:         action_handlers = {
647:             SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(
648:                 attempt, "session lost"
649:             ),
650:             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),
651:             SessionLossAction.CONTINUE: lambda: self._pending.clear(),
652:             SessionLossAction.FAIL: lambda: self._handle_work_error(
653:                 RuntimeError(f"Session lost during {attempt.spec.line!r}")
654:             ),
655:             SessionLossAction.VALIDATE: lambda: self._pending.clear(),
656:         }
657:         action_handlers[action]()
658: 
659:     def _restart_active_block(self, attempt, reason):
660:         retries = self._recovery_retries.get(attempt.block_index, 0)
661:         if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
662:             self._handle_work_error(RuntimeError(
663:                 f"{reason} repeatedly during {attempt.spec.line!r}; "
664:                 f"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})"
665:             ))
666:             return
667:         self._recovery_retries[attempt.block_index] = retries + 1
668:         self._pending = deque(self._active_commands)
669:         self._replay_context_target = self._block_prompt_context
670:         self._context_reset_attempted = False
671:         self.logger.warning(
672:             "%s during %s/%r; replaying block (command recovery %d/%d)",
673:             reason, self._active_feature.name, attempt.spec.line,
674:             retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,
675:         )
676: 
677:     def enqueue_runtime_feature(self, feature):
678:         return self.enqueue_runtime_features([feature])
679: 
680:     def enqueue_runtime_features(self, features):
681:         if not self._ready or self.busy:
682:             return False
683:         self._ready = False
684:         self._completed_messages.clear()
685:         for feature in reversed(features):
686:             self._features.appendleft(feature)
687:         return True

(End of file - total 687 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d3df88001xs2sD65FNXE5Cs",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3d625001pfFAbj0BYyugan",
  "callID": "call_8857160e5b2d4243b420a8b4",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_commander.py",
      "offset": 1,
      "limit": 700
    },
    "output": "<path>/source/head/fortinet/common/fos_commander.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n2: \n3: import datetime\n4: import re\n5: from collections import deque\n6: from contextlib import ExitStack\n7: from dataclasses import dataclass\n8: \n9: from .cli_commands import (\n10:     CleanupAction,\n11:     CommandAttempt,\n12:     CommandSequence,\n13:     CommandSpec,\n14:     ConfigBlock,\n15:     ContextLossAction,\n16:     SessionLossAction,\n17:     flatten_commands,\n18: )\n19: from .terminal import Data\n20: from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n21: \n22: DISPATCHABLE_COMPLETION_STATES = {\n23:     FOSCliState.CMD_PROMPT,\n24:     FOSCliState.CONFIRMATION,\n25:     FOSCliState.MULTILINE_PROMPT,\n26: }\n27: COMMAND_FAILURE_PATTERN = re.compile(\n28:     rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n29: )\n30: CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n31:     rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n32:     + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n33: )\n34: \n35: \n36: @dataclass\n37: class _StandardOutputContext:\n38:     feature: object\n39:     callback: object\n40:     phase: str = \"inspect\"\n41:     restore: bool = False\n42: \n43: \n44: class FOSCommander:\n45:     MAX_COMMAND_RECOVERY_RETRIES = 1\n46:     _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n47:     _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n48:     _CONSOLE_STANDARD_LINE = \"set output standard\"\n49: \n50:     def __init__(self, terminal, logger, continue_on_error=False):\n51:         self.terminal = terminal\n52:         self.logger = logger\n53:         self._features = deque()\n54:         self._active_feature = None\n55:         self._active_commands = ()\n56:         self._pending = deque()\n57:         self._inflight = None\n58:         self._attempt_number = 0\n59:         self._session_epoch = 0\n60:         self._recovering = False\n61:         self._cleanup = deque()\n62:         self._cleanup_actions = {}\n63:         self._in_cleanup = False\n64:         self._standard_output_context = None\n65:         self._suppression = ExitStack()\n66:         self._ready = False\n67:         self._startup_complete = False\n68:         self._feature_errors = []\n69:         self._authenticated_once = False\n70:         self._completed_messages = deque()\n71:         self._start_time = datetime.datetime.now()\n72:         self._continue_on_error = continue_on_error\n73:         self._pending_feature_error = None\n74:         self._current_state = None\n75:         self._callback_failed = False\n76:         self._prompt_context = None\n77:         self._block_prompt_context = None\n78:         self._recovery_retries = {}\n79:         self._cleanup_retries = {}\n80:         self._replay_context_target = None\n81:         self._context_reset_attempted = False\n82:         self._in_context_reset = False\n83: \n84:     def _call_feature(self, callback, *args):\n85:         \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n86:         try:\n87:             return callback(*args)\n88:         except Exception as error:\n89:             self._handle_work_error(error, from_callback=True)\n90:             return None\n91: \n92:     def _handle_work_error(self, error, *, from_callback=False):\n93:         \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n94:         if not self._continue_on_error:\n95:             raise error\n96:         if from_callback:\n97:             self.logger.exception(\"Bootstrap feature callback failed\")\n98:         else:\n99:             self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n100:         self._pending_feature_error = error\n101:         self._callback_failed = True\n102: \n103:     def _recover_feature_error(self, *, at_idle_prompt=False):\n104:         error = self._pending_feature_error\n105:         if error is None or (\n106:             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n107:         ):\n108:             return False\n109:         failed_work = self.continue_after_error(error, at_command_prompt=True)\n110:         if failed_work is None:\n111:             return False\n112:         self._pending_feature_error = None\n113:         self.logger.error(\n114:             \"Bootstrap work %s failed; continuing with remaining features \"\n115:             \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n116:             failed_work,\n117:         )\n118:         self._dispatch_next()\n119:         return True\n120: \n121:     @property\n122:     def ready(self):\n123:         return self._ready\n124: \n125:     @property\n126:     def busy(self):\n127:         return self._inflight is not None or bool(self._pending) or bool(self._cleanup)\n128: \n129:     @property\n130:     def startup_complete(self):\n131:         \"\"\"Whether the initial feature queue has drained, with or without errors.\"\"\"\n132:         return self._startup_complete\n133: \n134:     @property\n135:     def feature_errors(self):\n136:         \"\"\"Bootstrap feature errors recorded while best-effort mode is active.\"\"\"\n137:         return tuple(self._feature_errors)\n138: \n139:     def continue_after_error(self, error, at_command_prompt):\n140:         \"\"\"Skip failed work only when the CLI is back at a usable prompt.\n141: \n142:         A login rejection after the driver's credential recovery attempts, or\n143:         an error during an interactive prompt, cannot be recovered by sending\n144:         the next feature's commands, so automatic bootstrap must stop.\n145:         \"\"\"\n146:         if not at_command_prompt or self._ready:\n147:             return None\n148:         if self._active_feature is None and not self._in_cleanup:\n149:             return None\n150: \n151:         if self._active_feature is not None:\n152:             failed_name = self._active_feature.name\n153:             self._pending.clear()\n154:             self._active_commands = ()\n155:             self._inflight = None\n156:             self._suppression.close()\n157:             self._suppression = ExitStack()\n158:             self._finish_standard_output_context(self._active_feature)\n159:             self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n160:             self._active_feature = None\n161:         else:\n162:             failed_name = \"cleanup\"\n163:             self._inflight = None\n164:             self._suppression.close()\n165:             self._suppression = ExitStack()\n166: \n167:         self._in_cleanup = False\n168:         self._replay_context_target = None\n169:         self._in_context_reset = False\n170:         self._cleanup_retries.clear()\n171:         self._feature_errors.append((failed_name, str(error)))\n172:         return failed_name\n173: \n174:     def record_feature_error(self, name, error):\n175:         \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n176:         self._feature_errors.append((name, str(error)))\n177:         self.logger.info(\"Using recovery for %s: %s\", name, error)\n178: \n179:     def resolve_feature_error(self, name, resolution):\n180:         \"\"\"Clear a recoverable feature error after its condition is resolved.\"\"\"\n181:         remaining = [\n182:             (feature_name, error)\n183:             for feature_name, error in self._feature_errors\n184:             if feature_name != name\n185:         ]\n186:         resolved_count = len(self._feature_errors) - len(remaining)\n187:         if resolved_count:\n188:             self._feature_errors = remaining\n189:             self.logger.info(\n190:                 \"Resolved %s bootstrap recovery after %s\",\n191:                 name,\n192:                 resolution,\n193:             )\n194: \n195:     def start(self, features):\n196:         self._features.extend(features)\n197: \n198:     def tick(self):\n199:         if self._pending_feature_error is not None:\n200:             return\n201:         if self._active_feature and hasattr(self._active_feature, \"tick\"):\n202:             self._call_feature(self._active_feature.tick)\n203: \n204:     def submit_block(self, feature, block):\n205:         if feature is not self._active_feature:\n206:             raise RuntimeError(\"Inactive feature attempted to submit commands\")\n207:         if self.busy:\n208:             raise RuntimeError(\"Cannot replace an active command block\")\n209:         commands = tuple(flatten_commands(block))\n210:         self._active_commands = commands\n211:         self._pending = deque(commands)\n212:         self._block_prompt_context = self._prompt_context\n213:         self._recovery_retries = {}\n214:         self._replay_context_target = None\n215:         self._context_reset_attempted = False\n216: \n217:     def feature_complete(self, feature):\n218:         if feature is not self._active_feature:\n219:             return\n220:         if self.busy:\n221:             raise RuntimeError(\"Feature completed while commands are still pending\")\n222:         feature.mark_completed()\n223:         if feature.completion_message:\n224:             self._completed_messages.append(feature.completion_message)\n225:         self._finish_standard_output_context(feature)\n226:         self._schedule_feature_cleanup(feature, \"completion\")\n227:         self._active_feature = None\n228:         self._active_commands = ()\n229:         if not self._cleanup:\n230:             self._activate_next_feature()\n231: \n232:     def register_cleanup(self, feature, action):\n233:         if not isinstance(action, CleanupAction):\n234:             raise TypeError(\"cleanup must be a CleanupAction\")\n235:         self._cleanup_actions.setdefault(feature, []).append(action)\n236: \n237:     def with_standard_output(self, feature, callback):\n238:         \"\"\"Run a feature callback after standard console output is available.\"\"\"\n239:         if feature is not self._active_feature:\n240:             raise RuntimeError(\"Inactive feature requested standard console output\")\n241:         if self.busy or self._standard_output_context:\n242:             raise RuntimeError(\"Cannot start a standard console output context while busy\")\n243:         self._standard_output_context = _StandardOutputContext(feature, callback)\n244:         self.submit_block(feature, CommandSequence(\"console-output-inspect\", [\n245:             CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),\n246:         ]))\n247: \n248:     def _schedule_feature_cleanup(self, feature, trigger):\n249:         actions = self._cleanup_actions.pop(feature, [])\n250:         for action in actions:\n251:             if (trigger == \"completion\" and action.on_completion) or (\n252:                 trigger == \"interruption\" and action.on_interruption\n253:             ):\n254:                 self.logger.debug(f\"Scheduling cleanup {action.name} after {trigger}\")\n255:                 self._cleanup.extend(action.block.flatten())\n256: \n257:     def on_output(self, output):\n258:         if not isinstance(output, Data):\n259:             raise TypeError(\"commander output must be terminal.Data\")\n260:         if not output:\n261:             return output\n262:         if self._inflight:\n263:             if self._call_feature(self._inflight.on_output, output):\n264:                 return output\n265:             if self._active_feature and self._call_feature(self._active_feature.on_output, output):\n266:                 return output\n267:         self._inspect_output(output)\n268:         return output\n269: \n270:     def on_state(self, state, output):\n271:         \"\"\"Called by the driver for every recognized serial state.\"\"\"\n272:         self._current_state = state\n273:         self._callback_failed = False\n274:         if state == FOSCliState.CMD_PROMPT:\n275:             context = self._extract_prompt_context(output)\n276:             if context is not None:\n277:                 self._prompt_context = context\n278:             # Some releases return directly to a usable prompt after login,\n279:             # without a Welcome banner. The prompt also ends session recovery.\n280:             self._authenticated_once = True\n281:             self._recovering = False\n282:         if self._pending_feature_error is not None:\n283:             if state == FOSCliState.CMD_PROMPT:\n284:                 self._recover_feature_error()\n285:             elif state == FOSCliState.SESSION_LOST:\n286:                 self._session_epoch += 1\n287:                 self._recovering = True\n288:             elif state == FOSCliState.CREDENTIAL_ACCEPTED:\n289:                 self._authenticated_once = True\n290:                 self._recovering = False\n291:             return\n292:         self.on_output(output)\n293:         if self._callback_failed:\n294:             if state == FOSCliState.CMD_PROMPT:\n295:                 self._recover_feature_error()\n296:             return\n297:         if self._pending_feature_error is not None:\n298:             if state == FOSCliState.CMD_PROMPT:\n299:                 self._recover_feature_error()\n300:             return\n301: \n302:         if state == FOSCliState.SESSION_LOST:\n303:             self._handle_session_loss()\n304:             return\n305:         if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:\n306:             # Password updates can return to login without the explicit\n307:             # SESSION_LOST banner. Requeue the active command block so it is\n308:             # applied after the driver restores an accepted login.\n309:             self._handle_session_loss()\n310:             return\n311:         if state == FOSCliState.CREDENTIAL_ACCEPTED:\n312:             self._authenticated_once = True\n313:             self._recovering = False\n314:             return\n315:         if self._inflight and state in (\n316:             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n317:         ):\n318:             self._complete_inflight(state)\n319:             return\n320: \n321:         if state == FOSCliState.CMD_PROMPT and not self._recovering:\n322:             self._dispatch_next()\n323:         if self._callback_failed and state == FOSCliState.CMD_PROMPT:\n324:             self._recover_feature_error()\n325: \n326:     def on_prompt_echo(self, output):\n327:         \"\"\"Handle a prompt line that had trailing text after the prompt token.\"\"\"\n328:         if self.on_output(output).discarded:\n329:             return\n330:         self.logger.debug(\"Prompt had unexpected trailing output; requesting a clean prompt\")\n331:         self.terminal.write(b\"\\r\")\n332: \n333:     def _inspect_output(self, output):\n334:         if self._recovering:\n335:             output.discard()\n336: \n337:     def on_idle_prompt(self):\n338:         \"\"\"Recover errors or dispatch work while idle at a known prompt.\"\"\"\n339:         if self._inflight or self._recovering:\n340:             return\n341:         if self._pending_feature_error is not None:\n342:             # The driver calls this after a read timeout at a known CLI prompt.\n343:             # on_state has since recorded TN_TIMEOUT, so recover explicitly.\n344:             self._recover_feature_error(at_idle_prompt=True)\n345:             return\n346:         if self._pending or self._cleanup or self._active_feature is None:\n347:             self._dispatch_next()\n348: \n349:     def _activate_next_feature(self):\n350:         if self._ready or self._active_feature or self._recovering:\n351:             return\n352:         if not self._features:\n353:             if self._cleanup:\n354:                 return\n355:             self._ready = True\n356:             self.terminal.close()\n357:             if not self._startup_complete:\n358:                 self._startup_complete = True\n359:                 elapsed = datetime.datetime.now() - self._start_time\n360:                 if self._feature_errors:\n361:                     failed = \", \".join(name for name, _error in self._feature_errors)\n362:                     self.logger.error(\n363:                         \"Bootstrap reached the end with %d feature error(s) in %s; \"\n364:                         \"failed work: %s\",\n365:                         len(self._feature_errors),\n366:                         elapsed,\n367:                         failed,\n368:                     )\n369:                 else:\n370:                     self.logger.info(f\"Startup complete in {elapsed}\")\n371:             else:\n372:                 while self._completed_messages:\n373:                     self.logger.info(self._completed_messages.popleft())\n374:             return\n375:         self._active_feature = self._features.popleft()\n376:         self.logger.info(f\"Activating feature {self._active_feature.name}\")\n377:         self._call_feature(self._active_feature.begin_activation)\n378:         if self._pending_feature_error is None:\n379:             self._call_feature(self._active_feature.activate)\n380: \n381:     def _dispatch_next(self):\n382:         if self._inflight or self._recovering or self._pending_feature_error is not None:\n383:             return\n384:         if not self._restore_replay_context():\n385:             return\n386:         if not self._cleanup and self._active_feature is None:\n387:             self._activate_next_feature()\n388:             if self._active_feature is None:\n389:                 return\n390:         if self._cleanup:\n391:             spec = self._cleanup.popleft()\n392:             self._in_cleanup = True\n393:             block_index = None\n394:         elif not self._pending:\n395:             self._call_feature(self._active_feature.on_block_complete)\n396:             return\n397:         else:\n398:             spec = self._pending.popleft()\n399:             self._in_cleanup = False\n400:             block_index = len(self._active_commands) - len(self._pending) - 1\n401:         self._dispatch_command(spec, block_index)\n402: \n403:     def _dispatch_command(self, spec, block_index=None):\n404:         self._attempt_number += 1\n405:         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n406:         self._inflight.prompt_context_before = self._prompt_context\n407:         self._inflight.block_index = block_index\n408:         self._inflight.retry_count = (\n409:             self._cleanup_retries.get(id(spec), 0)\n410:             if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n411:         )\n412:         if self._active_feature and not self._in_context_reset:\n413:             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n414:             if self._pending_feature_error is not None:\n415:                 return\n416:         if spec.suppress_output:\n417:             self._suppression.enter_context(self.terminal.suppress_output())\n418:         self.logger.log(\n419:             TRACE_LEVEL,\n420:             f\"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/\"\n421:             f\"{spec.line!r}\"\n422:         )\n423:         self.terminal.write(f\"{spec.line}\\r\")\n424: \n425:     def _complete_inflight(self, state):\n426:         attempt = self._inflight\n427:         self._inflight = None\n428:         self._suppression.close()\n429:         self._suppression = ExitStack()\n430:         attempt.prompt_context_after = self._prompt_context\n431:         if self._in_context_reset:\n432:             self._in_context_reset = False\n433:             self._dispatch_next()\n434:             return\n435:         if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n436:             self._handle_context_loss(attempt)\n437:             if self._pending_feature_error is not None:\n438:                 self._recover_feature_error()\n439:             else:\n440:                 self._dispatch_next()\n441:             return\n442:         try:\n443:             self._validate_completion(attempt, state)\n444:         except RuntimeError as error:\n445:             if state != FOSCliState.CMD_PROMPT:\n446:                 # An interactive prompt cannot safely advance to another feature.\n447:                 raise\n448:             self._handle_work_error(error)\n449:             if self._pending_feature_error is not None:\n450:                 self._recover_feature_error()\n451:             return\n452:         if self._in_cleanup:\n453:             self._cleanup_retries.pop(id(attempt.spec), None)\n454:             self._in_cleanup = False\n455:             self._dispatch_next()\n456:             return\n457:         if self._is_standard_output_command(attempt.spec):\n458:             self._complete_standard_output_command(attempt)\n459:             if self._pending_feature_error is not None:\n460:                 return\n461:             if not self._recovering:\n462:                 self._dispatch_next()\n463:             return\n464:         completed_feature = self._active_feature\n465:         self._call_feature(completed_feature.on_command_executed, attempt, state)\n466:         if self._pending_feature_error is not None:\n467:             return\n468:         # The callback may have installed another block (confirmation/query path).\n469:         if not self.busy and self._active_feature is completed_feature:\n470:             self._call_feature(completed_feature.on_block_complete)\n471:         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n472:             self._dispatch_next()\n473: \n474:     @staticmethod\n475:     def _validate_completion(attempt, state):\n476:         if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n477:             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n478:         ):\n479:             raise RuntimeError(\n480:                 f\"FortiOS command {attempt.spec.line!r} failed \"\n481:                 f\"(return code {failure.group(1).decode()})\"\n482:             )\n483:         expected = attempt.spec.expected_completion_state\n484:         if expected is not None and state != expected:\n485:             raise RuntimeError(\n486:                 \"CLI command completed at unexpected prompt: \"\n487:                 f\"expected {expected.name}, received {state.name}\"\n488:             )\n489: \n490:     def _prompt_context_changed(self, attempt):\n491:         before = attempt.prompt_context_before\n492:         after = attempt.prompt_context_after\n493:         return (\n494:             before is not None\n495:             and after is not None\n496:             and before != after\n497:             and not self._command_may_change_context(attempt.spec)\n498:         )\n499: \n500:     def _handle_context_loss(self, attempt):\n501:         reason = (\n502:             \"CLI context changed from \"\n503:             f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n504:             f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n505:         )\n506:         if self._in_cleanup:\n507:             self._handle_work_error(RuntimeError(\n508:                 f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n509:             ))\n510:             return\n511:         action = self._call_feature(self._active_feature.on_context_loss, attempt)\n512:         if self._pending_feature_error is not None:\n513:             return\n514:         if action == ContextLossAction.RESTART_BLOCK:\n515:             self._restart_active_block(attempt, reason)\n516:         elif action == ContextLossAction.FAIL:\n517:             self._handle_work_error(RuntimeError(\n518:                 f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n519:             ))\n520:         else:\n521:             self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n522: \n523:     def _restore_replay_context(self):\n524:         \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n525:         target = self._replay_context_target\n526:         if target is None:\n527:             return True\n528:         if self._prompt_context == target:\n529:             self._replay_context_target = None\n530:             return True\n531:         if self._context_reset_attempted:\n532:             self._handle_work_error(RuntimeError(\n533:                 \"Unable to restore CLI context before replay: expected \"\n534:                 f\"{self._format_prompt_context(target)}, received \"\n535:                 f\"{self._format_prompt_context(self._prompt_context or ())}\"\n536:             ))\n537:             if self._pending_feature_error is not None:\n538:                 self._recover_feature_error()\n539:             return False\n540:         self._context_reset_attempted = True\n541:         self._in_context_reset = True\n542:         self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n543:         return False\n544: \n545:     @staticmethod\n546:     def _command_may_change_context(spec):\n547:         if spec.continuation:\n548:             return False\n549:         command = spec.line.strip().lower()\n550:         return (\n551:             command.startswith((\"config \", \"edit \"))\n552:             or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n553:             or command == \"set vdom-mode multi-vdom\"\n554:         )\n555: \n556:     @staticmethod\n557:     def _extract_prompt_context(output):\n558:         data = bytes(output)\n559:         matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n560:         if not matches:\n561:             return None\n562:         return tuple(\n563:             item.decode(errors=\"replace\")\n564:             for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n565:         )\n566: \n567:     @staticmethod\n568:     def _format_prompt_context(context):\n569:         return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n570: \n571:     def _is_standard_output_command(self, spec):\n572:         context = self._standard_output_context\n573:         return context is not None and (\n574:             spec.line == self._CONSOLE_INSPECT_LINE\n575:             or (context.phase == \"set-standard\" and not self._pending)\n576:         )\n577: \n578:     def _complete_standard_output_command(self, attempt):\n579:         context = self._standard_output_context\n580:         if attempt.spec.line == self._CONSOLE_INSPECT_LINE:\n581:             match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))\n582:             if not match or match.group(1) == b\"standard\":\n583:                 if not match:\n584:                     self.logger.warning(\"Could not determine console output mode; assuming standard output\")\n585:                 self._start_standard_output_callback(context)\n586:                 return\n587:             context.phase = \"set-standard\"\n588:             self.submit_block(context.feature, ConfigBlock(\"system console\", [\n589:                 self._CONSOLE_STANDARD_LINE,\n590:             ]))\n591:             return\n592:         if context.phase == \"set-standard\":\n593:             context.restore = True\n594:             self._start_standard_output_callback(context)\n595: \n596:     def _start_standard_output_callback(self, context):\n597:         context.phase = \"active\"\n598:         self._call_feature(context.callback)\n599: \n600:     def _finish_standard_output_context(self, feature):\n601:         context = self._standard_output_context\n602:         if context is None or context.feature is not feature:\n603:             return\n604:         self._standard_output_context = None\n605:         if context.restore:\n606:             self._cleanup.extend(ConfigBlock(\"system console\", [\n607:                 \"set output more\",\n608:             ]).flatten())\n609: \n610:     def _handle_session_loss(self):\n611:         self._session_epoch += 1\n612:         self._recovering = True\n613:         if not self._inflight:\n614:             return\n615:         attempt = self._inflight\n616:         self._inflight = None\n617:         self._suppression.close()\n618:         self._suppression = ExitStack()\n619:         if self._in_context_reset:\n620:             # Login may itself restore the target scope. The pending replay\n621:             # stays bounded by the original command's recovery allowance.\n622:             self._in_context_reset = False\n623:             return\n624:         if self._in_cleanup:\n625:             retries = self._cleanup_retries.get(id(attempt.spec), 0)\n626:             if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n627:                 self._handle_work_error(RuntimeError(\n628:                     f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n629:                     \"retry limit reached\"\n630:                 ))\n631:                 return\n632:             self._cleanup_retries[id(attempt.spec)] = retries + 1\n633:             self._cleanup.appendleft(attempt.spec)\n634:             self._in_cleanup = False\n635:             return\n636:         self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n637:         action = self._call_feature(\n638:             self._active_feature.on_session_loss,\n639:             attempt,\n640:         )\n641:         if self._pending_feature_error is not None:\n642:             return\n643:         self.logger.info(\n644:             f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n645:         )\n646:         action_handlers = {\n647:             SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n648:                 attempt, \"session lost\"\n649:             ),\n650:             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n651:             SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n652:             SessionLossAction.FAIL: lambda: self._handle_work_error(\n653:                 RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n654:             ),\n655:             SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n656:         }\n657:         action_handlers[action]()\n658: \n659:     def _restart_active_block(self, attempt, reason):\n660:         retries = self._recovery_retries.get(attempt.block_index, 0)\n661:         if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n662:             self._handle_work_error(RuntimeError(\n663:                 f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n664:                 f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n665:             ))\n666:             return\n667:         self._recovery_retries[attempt.block_index] = retries + 1\n668:         self._pending = deque(self._active_commands)\n669:         self._replay_context_target = self._block_prompt_context\n670:         self._context_reset_attempted = False\n671:         self.logger.warning(\n672:             \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n673:             reason, self._active_feature.name, attempt.spec.line,\n674:             retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n675:         )\n676: \n677:     def enqueue_runtime_feature(self, feature):\n678:         return self.enqueue_runtime_features([feature])\n679: \n680:     def enqueue_runtime_features(self, features):\n681:         if not self._ready or self.busy:\n682:             return False\n683:         self._ready = False\n684:         self._completed_messages.clear()\n685:         for feature in reversed(features):\n686:             self._features.appendleft(feature)\n687:         return True\n\n(End of file - total 687 lines)\n</content>",
    "title": "source/head/fortinet/common/fos_commander.py",
    "metadata": {
      "preview": "\"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n\nimport datetime\nimport re\nfrom collections import deque\nfrom contextlib import ExitStack\nfrom dataclasses import dataclass\n\nfrom .cli_commands import (\n    CleanupAction,\n    CommandAttempt,\n    CommandSequence,\n    CommandSpec,\n    ConfigBlock,\n    ContextLossAction,\n    SessionLossAction,\n    flatten_commands,\n)\nfrom .terminal import Data\nfrom .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_commander.py",
        "text": "\"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n\nimport datetime\nimport re\nfrom collections import deque\nfrom contextlib import ExitStack\nfrom dataclasses import dataclass\n\nfrom .cli_commands import (\n    CleanupAction,\n    CommandAttempt,\n    CommandSequence,\n    CommandSpec,\n    ConfigBlock,\n    ContextLossAction,\n    SessionLossAction,\n    flatten_commands,\n)\nfrom .terminal import Data\nfrom .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n\nDISPATCHABLE_COMPLETION_STATES = {\n    FOSCliState.CMD_PROMPT,\n    FOSCliState.CONFIRMATION,\n    FOSCliState.MULTILINE_PROMPT,\n}\nCOMMAND_FAILURE_PATTERN = re.compile(\n    rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n)\nCLI_PROMPT_CONTEXT_PATTERN = re.compile(\n    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n)\n\n\n@dataclass\nclass _StandardOutputContext:\n    feature: object\n    callback: object\n    phase: str = \"inspect\"\n    restore: bool = False\n\n\nclass FOSCommander:\n    MAX_COMMAND_RECOVERY_RETRIES = 1\n    _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n    _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n    _CONSOLE_STANDARD_LINE = \"set output standard\"\n\n    def __init__(self, terminal, logger, continue_on_error=False):\n        self.terminal = terminal\n        self.logger = logger\n        self._features = deque()\n        self._active_feature = None\n        self._active_commands = ()\n        self._pending = deque()\n        self._inflight = None\n        self._attempt_number = 0\n        self._session_epoch = 0\n        self._recovering = False\n        self._cleanup = deque()\n        self._cleanup_actions = {}\n        self._in_cleanup = False\n        self._standard_output_context = None\n        self._suppression = ExitStack()\n        self._ready = False\n        self._startup_complete = False\n        self._feature_errors = []\n        self._authenticated_once = False\n        self._completed_messages = deque()\n        self._start_time = datetime.datetime.now()\n        self._continue_on_error = continue_on_error\n        self._pending_feature_error = None\n        self._current_state = None\n        self._callback_failed = False\n        self._prompt_context = None\n        self._block_prompt_context = None\n        self._recovery_retries = {}\n        self._cleanup_retries = {}\n        self._replay_context_target = None\n        self._context_reset_attempted = False\n        self._in_context_reset = False\n\n    def _call_feature(self, callback, *args):\n        \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n        try:\n            return callback(*args)\n        except Exception as error:\n            self._handle_work_error(error, from_callback=True)\n            return None\n\n    def _handle_work_error(self, error, *, from_callback=False):\n        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n        if not self._continue_on_error:\n            raise error\n        if from_callback:\n            self.logger.exception(\"Bootstrap feature callback failed\")\n        else:\n            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n        self._pending_feature_error = error\n        self._callback_failed = True\n\n    def _recover_feature_error(self, *, at_idle_prompt=False):\n        error = self._pending_feature_error\n        if error is None or (\n            self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n        ):\n            return False\n        failed_work = self.continue_after_error(error, at_command_prompt=True)\n        if failed_work is None:\n            return False\n        self._pending_feature_error = None\n        self.logger.error(\n            \"Bootstrap work %s failed; continuing with remaining features \"\n            \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n            failed_work,\n        )\n        self._dispatch_next()\n        return True\n\n    @property\n    def ready(self):\n        return self._ready\n\n    @property\n    def busy(self):\n        return self._inflight is not None or bool(self._pending) or bool(self._cleanup)\n\n    @property\n    def startup_complete(self):\n        \"\"\"Whether the initial feature queue has drained, with or without errors.\"\"\"\n        return self._startup_complete\n\n    @property\n    def feature_errors(self):\n        \"\"\"Bootstrap feature errors recorded while best-effort mode is active.\"\"\"\n        return tuple(self._feature_errors)\n\n    def continue_after_error(self, error, at_command_prompt):\n        \"\"\"Skip failed work only when the CLI is back at a usable prompt.\n\n        A login rejection after the driver's credential recovery attempts, or\n        an error during an interactive prompt, cannot be recovered by sending\n        the next feature's commands, so automatic bootstrap must stop.\n        \"\"\"\n        if not at_command_prompt or self._ready:\n            return None\n        if self._active_feature is None and not self._in_cleanup:\n            return None\n\n        if self._active_feature is not None:\n            failed_name = self._active_feature.name\n            self._pending.clear()\n            self._active_commands = ()\n            self._inflight = None\n            self._suppression.close()\n            self._suppression = ExitStack()\n            self._finish_standard_output_context(self._active_feature)\n            self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n            self._active_feature = None\n        else:\n            failed_name = \"cleanup\"\n            self._inflight = None\n            self._suppression.close()\n            self._suppression = ExitStack()\n\n        self._in_cleanup = False\n        self._replay_context_target = None\n        self._in_context_reset = False\n        self._cleanup_retries.clear()\n        self._feature_errors.append((failed_name, str(error)))\n        return failed_name\n\n    def record_feature_error(self, name, error):\n        \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n        self._feature_errors.append((name, str(error)))\n        self.logger.info(\"Using recovery for %s: %s\", name, error)\n\n    def resolve_feature_error(self, name, resolution):\n        \"\"\"Clear a recoverable feature error after its condition is resolved.\"\"\"\n        remaining = [\n            (feature_name, error)\n            for feature_name, error in self._feature_errors\n            if feature_name != name\n        ]\n        resolved_count = len(self._feature_errors) - len(remaining)\n        if resolved_count:\n            self._feature_errors = remaining\n            self.logger.info(\n                \"Resolved %s bootstrap recovery after %s\",\n                name,\n                resolution,\n            )\n\n    def start(self, features):\n        self._features.extend(features)\n\n    def tick(self):\n        if self._pending_feature_error is not None:\n            return\n        if self._active_feature and hasattr(self._active_feature, \"tick\"):\n            self._call_feature(self._active_feature.tick)\n\n    def submit_block(self, feature, block):\n        if feature is not self._active_feature:\n            raise RuntimeError(\"Inactive feature attempted to submit commands\")\n        if self.busy:\n            raise RuntimeError(\"Cannot replace an active command block\")\n        commands = tuple(flatten_commands(block))\n        self._active_commands = commands\n        self._pending = deque(commands)\n        self._block_prompt_context = self._prompt_context\n        self._recovery_retries = {}\n        self._replay_context_target = None\n        self._context_reset_attempted = False\n\n    def feature_complete(self, feature):\n        if feature is not self._active_feature:\n            return\n        if self.busy:\n            raise RuntimeError(\"Feature completed while commands are still pending\")\n        feature.mark_completed()\n        if feature.completion_message:\n            self._completed_messages.append(feature.completion_message)\n        self._finish_standard_output_context(feature)\n        self._schedule_feature_cleanup(feature, \"completion\")\n        self._active_feature = None\n        self._active_commands = ()\n        if not self._cleanup:\n            self._activate_next_feature()\n\n    def register_cleanup(self, feature, action):\n        if not isinstance(action, CleanupAction):\n            raise TypeError(\"cleanup must be a CleanupAction\")\n        self._cleanup_actions.setdefault(feature, []).append(action)\n\n    def with_standard_output(self, feature, callback):\n        \"\"\"Run a feature callback after standard console output is available.\"\"\"\n        if feature is not self._active_feature:\n            raise RuntimeError(\"Inactive feature requested standard console output\")\n        if self.busy or self._standard_output_context:\n            raise RuntimeError(\"Cannot start a standard console output context while busy\")\n        self._standard_output_context = _StandardOutputContext(feature, callback)\n        self.submit_block(feature, CommandSequence(\"console-output-inspect\", [\n            CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),\n        ]))\n\n    def _schedule_feature_cleanup(self, feature, trigger):\n        actions = self._cleanup_actions.pop(feature, [])\n        for action in actions:\n            if (trigger == \"completion\" and action.on_completion) or (\n                trigger == \"interruption\" and action.on_interruption\n            ):\n                self.logger.debug(f\"Scheduling cleanup {action.name} after {trigger}\")\n                self._cleanup.extend(action.block.flatten())\n\n    def on_output(self, output):\n        if not isinstance(output, Data):\n            raise TypeError(\"commander output must be terminal.Data\")\n        if not output:\n            return output\n        if self._inflight:\n            if self._call_feature(self._inflight.on_output, output):\n                return output\n            if self._active_feature and self._call_feature(self._active_feature.on_output, output):\n                return output\n        self._inspect_output(output)\n        return output\n\n    def on_state(self, state, output):\n        \"\"\"Called by the driver for every recognized serial state.\"\"\"\n        self._current_state = state\n        self._callback_failed = False\n        if state == FOSCliState.CMD_PROMPT:\n            context = self._extract_prompt_context(output)\n            if context is not None:\n                self._prompt_context = context\n            # Some releases return directly to a usable prompt after login,\n            # without a Welcome banner. The prompt also ends session recovery.\n            self._authenticated_once = True\n            self._recovering = False\n        if self._pending_feature_error is not None:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            elif state == FOSCliState.SESSION_LOST:\n                self._session_epoch += 1\n                self._recovering = True\n            elif state == FOSCliState.CREDENTIAL_ACCEPTED:\n                self._authenticated_once = True\n                self._recovering = False\n            return\n        self.on_output(output)\n        if self._callback_failed:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            return\n        if self._pending_feature_error is not None:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            return\n\n        if state == FOSCliState.SESSION_LOST:\n            self._handle_session_loss()\n            return\n        if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:\n            # Password updates can return to login without the explicit\n            # SESSION_LOST banner. Requeue the active command block so it is\n            # applied after the driver restores an accepted login.\n            self._handle_session_loss()\n            return\n        if state == FOSCliState.CREDENTIAL_ACCEPTED:\n            self._authenticated_once = True\n            self._recovering = False\n            return\n        if self._inflight and state in (\n            self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n        ):\n            self._complete_inflight(state)\n            return\n\n        if state == FOSCliState.CMD_PROMPT and not self._recovering:\n            self._dispatch_next()\n        if self._callback_failed and state == FOSCliState.CMD_PROMPT:\n            self._recover_feature_error()\n\n    def on_prompt_echo(self, output):\n        \"\"\"Handle a prompt line that had trailing text after the prompt token.\"\"\"\n        if self.on_output(output).discarded:\n            return\n        self.logger.debug(\"Prompt had unexpected trailing output; requesting a clean prompt\")\n        self.terminal.write(b\"\\r\")\n\n    def _inspect_output(self, output):\n        if self._recovering:\n            output.discard()\n\n    def on_idle_prompt(self):\n        \"\"\"Recover errors or dispatch work while idle at a known prompt.\"\"\"\n        if self._inflight or self._recovering:\n            return\n        if self._pending_feature_error is not None:\n            # The driver calls this after a read timeout at a known CLI prompt.\n            # on_state has since recorded TN_TIMEOUT, so recover explicitly.\n            self._recover_feature_error(at_idle_prompt=True)\n            return\n        if self._pending or self._cleanup or self._active_feature is None:\n            self._dispatch_next()\n\n    def _activate_next_feature(self):\n        if self._ready or self._active_feature or self._recovering:\n            return\n        if not self._features:\n            if self._cleanup:\n                return\n            self._ready = True\n            self.terminal.close()\n            if not self._startup_complete:\n                self._startup_complete = True\n                elapsed = datetime.datetime.now() - self._start_time\n                if self._feature_errors:\n                    failed = \", \".join(name for name, _error in self._feature_errors)\n                    self.logger.error(\n                        \"Bootstrap reached the end with %d feature error(s) in %s; \"\n                        \"failed work: %s\",\n                        len(self._feature_errors),\n                        elapsed,\n                        failed,\n                    )\n                else:\n                    self.logger.info(f\"Startup complete in {elapsed}\")\n            else:\n                while self._completed_messages:\n                    self.logger.info(self._completed_messages.popleft())\n            return\n        self._active_feature = self._features.popleft()\n        self.logger.info(f\"Activating feature {self._active_feature.name}\")\n        self._call_feature(self._active_feature.begin_activation)\n        if self._pending_feature_error is None:\n            self._call_feature(self._active_feature.activate)\n\n    def _dispatch_next(self):\n        if self._inflight or self._recovering or self._pending_feature_error is not None:\n            return\n        if not self._restore_replay_context():\n            return\n        if not self._cleanup and self._active_feature is None:\n            self._activate_next_feature()\n            if self._active_feature is None:\n                return\n        if self._cleanup:\n            spec = self._cleanup.popleft()\n            self._in_cleanup = True\n            block_index = None\n        elif not self._pending:\n            self._call_feature(self._active_feature.on_block_complete)\n            return\n        else:\n            spec = self._pending.popleft()\n            self._in_cleanup = False\n            block_index = len(self._active_commands) - len(self._pending) - 1\n        self._dispatch_command(spec, block_index)\n\n    def _dispatch_command(self, spec, block_index=None):\n        self._attempt_number += 1\n        self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n        self._inflight.prompt_context_before = self._prompt_context\n        self._inflight.block_index = block_index\n        self._inflight.retry_count = (\n            self._cleanup_retries.get(id(spec), 0)\n            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n        )\n        if self._active_feature and not self._in_context_reset:\n            self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n            if self._pending_feature_error is not None:\n                return\n        if spec.suppress_output:\n            self._suppression.enter_context(self.terminal.suppress_output())\n        self.logger.log(\n            TRACE_LEVEL,\n            f\"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/\"\n            f\"{spec.line!r}\"\n        )\n        self.terminal.write(f\"{spec.line}\\r\")\n\n    def _complete_inflight(self, state):\n        attempt = self._inflight\n        self._inflight = None\n        self._suppression.close()\n        self._suppression = ExitStack()\n        attempt.prompt_context_after = self._prompt_context\n        if self._in_context_reset:\n            self._in_context_reset = False\n            self._dispatch_next()\n            return\n        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n            self._handle_context_loss(attempt)\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            else:\n                self._dispatch_next()\n            return\n        try:\n            self._validate_completion(attempt, state)\n        except RuntimeError as error:\n            if state != FOSCliState.CMD_PROMPT:\n                # An interactive prompt cannot safely advance to another feature.\n                raise\n            self._handle_work_error(error)\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            return\n        if self._in_cleanup:\n            self._cleanup_retries.pop(id(attempt.spec), None)\n            self._in_cleanup = False\n            self._dispatch_next()\n            return\n        if self._is_standard_output_command(attempt.spec):\n            self._complete_standard_output_command(attempt)\n            if self._pending_feature_error is not None:\n                return\n            if not self._recovering:\n                self._dispatch_next()\n            return\n        completed_feature = self._active_feature\n        self._call_feature(completed_feature.on_command_executed, attempt, state)\n        if self._pending_feature_error is not None:\n            return\n        # The callback may have installed another block (confirmation/query path).\n        if not self.busy and self._active_feature is completed_feature:\n            self._call_feature(completed_feature.on_block_complete)\n        if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n            self._dispatch_next()\n\n    @staticmethod\n    def _validate_completion(attempt, state):\n        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n            failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n        ):\n            raise RuntimeError(\n                f\"FortiOS command {attempt.spec.line!r} failed \"\n                f\"(return code {failure.group(1).decode()})\"\n            )\n        expected = attempt.spec.expected_completion_state\n        if expected is not None and state != expected:\n            raise RuntimeError(\n                \"CLI command completed at unexpected prompt: \"\n                f\"expected {expected.name}, received {state.name}\"\n            )\n\n    def _prompt_context_changed(self, attempt):\n        before = attempt.prompt_context_before\n        after = attempt.prompt_context_after\n        return (\n            before is not None\n            and after is not None\n            and before != after\n            and not self._command_may_change_context(attempt.spec)\n        )\n\n    def _handle_context_loss(self, attempt):\n        reason = (\n            \"CLI context changed from \"\n            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n        )\n        if self._in_cleanup:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n            ))\n            return\n        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n        if self._pending_feature_error is not None:\n            return\n        if action == ContextLossAction.RESTART_BLOCK:\n            self._restart_active_block(attempt, reason)\n        elif action == ContextLossAction.FAIL:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n            ))\n        else:\n            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n\n    def _restore_replay_context(self):\n        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n        target = self._replay_context_target\n        if target is None:\n            return True\n        if self._prompt_context == target:\n            self._replay_context_target = None\n            return True\n        if self._context_reset_attempted:\n            self._handle_work_error(RuntimeError(\n                \"Unable to restore CLI context before replay: expected \"\n                f\"{self._format_prompt_context(target)}, received \"\n                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n            ))\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            return False\n        self._context_reset_attempted = True\n        self._in_context_reset = True\n        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n        return False\n\n    @staticmethod\n    def _command_may_change_context(spec):\n        if spec.continuation:\n            return False\n        command = spec.line.strip().lower()\n        return (\n            command.startswith((\"config \", \"edit \"))\n            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n            or command == \"set vdom-mode multi-vdom\"\n        )\n\n    @staticmethod\n    def _extract_prompt_context(output):\n        data = bytes(output)\n        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n        if not matches:\n            return None\n        return tuple(\n            item.decode(errors=\"replace\")\n            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n        )\n\n    @staticmethod\n    def _format_prompt_context(context):\n        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n\n    def _is_standard_output_command(self, spec):\n        context = self._standard_output_context\n        return context is not None and (\n            spec.line == self._CONSOLE_INSPECT_LINE\n            or (context.phase == \"set-standard\" and not self._pending)\n        )\n\n    def _complete_standard_output_command(self, attempt):\n        context = self._standard_output_context\n        if attempt.spec.line == self._CONSOLE_INSPECT_LINE:\n            match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))\n            if not match or match.group(1) == b\"standard\":\n                if not match:\n                    self.logger.warning(\"Could not determine console output mode; assuming standard output\")\n                self._start_standard_output_callback(context)\n                return\n            context.phase = \"set-standard\"\n            self.submit_block(context.feature, ConfigBlock(\"system console\", [\n                self._CONSOLE_STANDARD_LINE,\n            ]))\n            return\n        if context.phase == \"set-standard\":\n            context.restore = True\n            self._start_standard_output_callback(context)\n\n    def _start_standard_output_callback(self, context):\n        context.phase = \"active\"\n        self._call_feature(context.callback)\n\n    def _finish_standard_output_context(self, feature):\n        context = self._standard_output_context\n        if context is None or context.feature is not feature:\n            return\n        self._standard_output_context = None\n        if context.restore:\n            self._cleanup.extend(ConfigBlock(\"system console\", [\n                \"set output more\",\n            ]).flatten())\n\n    def _handle_session_loss(self):\n        self._session_epoch += 1\n        self._recovering = True\n        if not self._inflight:\n            return\n        attempt = self._inflight\n        self._inflight = None\n        self._suppression.close()\n        self._suppression = ExitStack()\n        if self._in_context_reset:\n            # Login may itself restore the target scope. The pending replay\n            # stays bounded by the original command's recovery allowance.\n            self._in_context_reset = False\n            return\n        if self._in_cleanup:\n            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n                self._handle_work_error(RuntimeError(\n                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n                    \"retry limit reached\"\n                ))\n                return\n            self._cleanup_retries[id(attempt.spec)] = retries + 1\n            self._cleanup.appendleft(attempt.spec)\n            self._in_cleanup = False\n            return\n        self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n        action = self._call_feature(\n            self._active_feature.on_session_loss,\n            attempt,\n        )\n        if self._pending_feature_error is not None:\n            return\n        self.logger.info(\n            f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n        )\n        action_handlers = {\n            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n                attempt, \"session lost\"\n            ),\n            SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n            SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n            SessionLossAction.FAIL: lambda: self._handle_work_error(\n                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n            ),\n            SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n        }\n        action_handlers[action]()\n\n    def _restart_active_block(self, attempt, reason):\n        retries = self._recovery_retries.get(attempt.block_index, 0)\n        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n            ))\n            return\n        self._recovery_retries[attempt.block_index] = retries + 1\n        self._pending = deque(self._active_commands)\n        self._replay_context_target = self._block_prompt_context\n        self._context_reset_attempted = False\n        self.logger.warning(\n            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n            reason, self._active_feature.name, attempt.spec.line,\n            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n        )\n\n    def enqueue_runtime_feature(self, feature):\n        return self.enqueue_runtime_features([feature])\n\n    def enqueue_runtime_features(self, features):\n        if not self._ready or self.busy:\n            return False\n        self._ready = False\n        self._completed_messages.clear()\n        for feature in reversed(features):\n            self._features.appendleft(feature)\n        return True",
        "lineStart": 1,
        "lineEnd": 687,
        "totalLines": 687,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716379532,
      "end": 1793716379537
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d3df930019bH103r0jdUimv",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3d625001pfFAbj0BYyugan",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 15755,
    "input": 15599,
    "output": 102,
    "reasoning": 54,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d3d625001pfFAbj0BYyugan",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716377125,
    "completed": 1793716379542
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 15755,
    "input": 15599,
    "output": 102,
    "reasoning": 54,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 15
step-start
{
  "type": "step-start",
  "id": "prt_1a1d3e79c001vtomU1Y2UQsNKc",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3df9a001Z6KRG0YbSMbHXs"
}
Reasoning
Now I have the full fos_commander.py. Let me check the remaining test file test_common_stack_boundaries.py, the rest of test_common_stack_parsing.py (I read it before per handoff but should check), features/license.py on_output, and the README diffs, plus pki.py diff. Also check the diff for what changed in base.py, credentials.py, terminal.py, etc. Let me look at the diff to know what changed vs base.

Key concerns to verify:
1. `_complete_inflight` ordering: context-loss check before `_validate_completion`. Wait — actually looking at lines 435-441: `if state == CMD_PROMPT and self._prompt_context_changed(attempt)` → `_handle_context_loss`. But note `attempt.prompt_context_after = self._prompt_context` set at line 430. The scope-commit failure check (`closes_scope` + failure pattern) is in `_validate_completion`, which runs only if context did NOT change. Hmm, but the handoff noted "context-loss check precedes `_validate_completion`... so a failing `next`/`end` that also changes context takes the restart path instead of the 'always fatal' failure path." Let me think: a `next` command that fails with "Command fail. Return code -542." — does the prompt context change? No, a failed `next` returns to same prompt. So prompt_context_before == after, no context loss, and _validate_completion catches failure. The test `test_closing_failure_with_same_prompt_still_ejects` covers code "0","7","-61" with same prompt → error. OK.

But wait: could a failing `next` change context? FortiOS `next` on failure stays in edit mode → context same. So the ordering is probably fine. But what about the success path: `next` succeeds and context changes (exits edit block) → `_prompt_context_changed` check: `before != after and not self._command_may_change_context(attempt.spec)`. `next` IS in the set {next, end, abort...} → `_command_may_change_context` returns True → not considered context loss. Good. But then for a successful `next`, after `_command_may_change_context` says may change, no context loss. Good.

But there's subtlety: `_prompt_context_changed` requires before and after both not None. If the after-context extraction fails (None), context loss is not detected. Hmm — `_extract_prompt_context` returns None if no match in output. `_prompt_context` retains previous value. So if a prompt output doesn't match the pattern (e.g. hostname mismatch), context stays at previous value. That's pre-existing behavior maybe.

2. The `on_output` full-buffer semantics for features. Let me check features/license.py on_output and base.py. Also features like startup_config, pki — do they consume `on_output`? The grep found only base.py and license.py define on_output. base.py line 46 — probably a no-op hook returning False. license.py line 97 — let me read.

Also need to check other expect( callers in features — grep only searched for expect( in features and found none besides? The grep pattern was `def on_output|discard\(|expect\(` and only found 2 matches, meaning features don't call expect or discard directly. So the terminal buffer semantics mainly affect driver/commander. Features read output via on_output(attempt, output)? Let me check how features receive captured output — via attempt.on_output? Actually `CommandAttempt.on_output` in cli_commands. Let me read cli_commands.py fully to check.

3. `_dispatch_command`: `_recovery_retries.get(block_index, 0)` — block_index None for cleanup; fine.

Note: `_dispatch_command` computes `block_index = len(self._active_commands) - len(self._pending) - 1`. When replaying after restart_block, `_pending` is reset to full `self._active_commands`, so block_index recalculates to 0 for first command. Retry keyed by block_index — correct.

But in `_handle_session_loss` for non-cleanup path: it pops attempt, then calls `_schedule_feature_cleanup` and `on_session_loss` — action handlers. RESTART_BLOCK → `_restart_active_block(attempt, ...)` which uses `attempt.block_index`. OK.

4. `_restore_replay_context` with target None returns True immediately — fine; target is None when no replay pending.

But note `submit_block` sets `self._replay_context_target = None` — so new block clears pending replay. OK.

Edge: `_restart_active_block` sets `_replay_context_target = self._block_prompt_context`. If `_block_prompt_context` is None (e.g., prompt context never extracted because prompt pattern didn't include context? Actually `_extract_prompt_context` returns tuple possibly empty `()`), then target None → `_restore_replay_context` returns True without abort. Fine—means can't determine context.

5. `test_failed_context_reset_does_not_loop`: after abort, prompt still shows "interface" context → `_restore_replay_context` again → `_context_reset_attempted` True → error. Bounded. Good.

6. `id(spec)` keys for `_cleanup_retries`: cleanup specs come from `action.block.flatten()` — each call to `_schedule_feature_cleanup` creates new spec objects? `flatten()` probably creates CommandSpec objects. `id()` reuse after GC could theoretically collide but specs are retained in `_cleanup` deque while keyed, so no live collision while in deque. But `_cleanup_retries` entries are only popped in `_complete_inflight` (line 453). If cleanup retry fails via `continue_after_error`, `_cleanup_retries.clear()` at line 170. If `_handle_session_loss` fails with retry limit → `_handle_work_error` → raise or pending error. Entries could linger keyed by dead objects, but cleared eventually. Minor.

Actually there's a subtle issue: `_dispatch_command` for cleanup pops spec from `_cleanup`; if session lost, spec is appended back via `appendleft`. Fine.

7. The concern about duplicate consumption: terminal timeout Data now exposes full retained buffer. Features receive output via `commander.on_output` → `_inflight.on_output`. Only if inflight exists. `CommandAttempt.on_output` appends bytes to attempt.output presumably with discard semantics. Let me read cli_commands.py to confirm.

8. `on_state` CMD_PROMPT reset: at top of on_state, for CMD_PROMPT sets `_authenticated_once = True; _recovering = False`. Hmm, that means CMD_PROMPT clears recovering even if the login was not actually complete? Pre-existing? The handoff says "on_state top-of-function CMD_PROMPT reset" was noted. Whatever.

9. `_complete_inflight` when `_in_context_reset` (abort dispatched): on completion at CMD_PROMPT, dispatch_next → `_restore_replay_context` re-checks context. Good.

10. Now the scope-failure + capture: `attempt.output` — `COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))`. attempt.output accumulates from `on_output` calls. For `closes_scope` commands, output includes the "Command fail. Return code -542." lines. But with the new timeout semantics, `on_output` is only invoked... where? In driver `_handle_state`? Let me check how the driver passes output to commander. In `test_closing_failure_cannot_be_disabled_or_replayed`, chunks are fed via `commander.on_output(Data(chunk))` directly while prompt context hasn't arrived yet... wait they feed chunks before the prompt; but the failure pattern is searched from `attempt.output` at `_complete_inflight`. The chunks get appended by `attempt.on_output`. Note `attempt.on_output(output)` returns truthy? In commander.on_output: `if self._call_feature(self._inflight.on_output, output): return output`. So attempt.on_output returning True means consumed.

Wait — in the test, they call `commander.on_output(data)` and assert `data.discarded`. So attempt.on_output must discard. Need to read cli_commands.py.

11. Now, the potential duplicate-consumption issue: terminal timeout Data exposes FULL retained buffer on each timeout. The driver passes the Data to commander.on_output (probably). If commander's attempt.on_output appends the full buffer bytes to attempt.output each time, repeated timeouts would duplicate content into attempt.output, potentially causing false failure-pattern matches or duplicated capture. Tests: `test_timeout_capture_consumes_retained_prefix_and_new_bytes` shows attempt.on_output(output) → output bytes = prefix+chunk, and buffer becomes empty — meaning on_output discards the whole view. And `test_timeout_inspection_sees_a_token_completed_by_new_input` shows that on timeout without discard, buffer retains. So if the driver passes timeout Data to commander.on_output without discarding, and the commander's inflight.on_output discards it... then fine. But if inflight is None (no active command), `_inspect_output` discards only when `_recovering`. Otherwise the buffer keeps growing until buffer limit → error at limit. That's the design: retained buffer consumed by next expect().

Hmm, but what about the driver: on TN_TIMEOUT, driver passes Data to commander.on_state(TN_TIMEOUT, Data)? In `test_prompt_patterns_responses_and_state_callbacks`, `driver._process_state(FOSCliState.TN_TIMEOUT, Data(b""))` → commander.on_idle_prompt called. Does commander.on_state get called with the timeout Data and then on_output? In on_state, `self.on_output(output)` is called after pending-error checks — for TN_TIMEOUT with Data(b"")... on_output returns early if not output. For timeout with non-empty retained buffer, on_output would be invoked each spin with the same full buffer → inflight.on_output appends duplicates to attempt.output? But wait — does the driver call commander.on_output for timeout output? Let me read fos_cli_driver.py fully to trace _handle_state / _next_state / TN_TIMEOUT handling.

Let me now read:
- fos_cli_driver.py (full)
- cli_commands.py (full)
- features/base.py, features/license.py on_output
- test_common_stack_boundaries.py
- README diffs and pki.py diff from diff.txt (I've read the diff; need to recall pki comment change and README changes — I read diff.txt earlier per handoff; but I don't have its content in this context. I should re-read relevant parts of diff.txt.)

Let me batch reads.
The commander flow is now clear. Next, I need to trace how the driver routes timeout output into the commander, and how `CommandAttempt.on_output` consumes `Data` views — that's where duplicate-consumption risk would live.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/cli_commands.py"
}

Output

<path>/source/head/fortinet/common/cli_commands.py</path>
<type>file</type>
<content>
1: """Command and scope data used by the FortiOS CLI scheduler."""
2: 
3: from dataclasses import dataclass, field
4: from enum import Enum, auto
5: 
6: from .common import FOSCliState
7: 
8: 
9: class SessionLossAction(Enum):
10:     RESTART_BLOCK = auto()
11:     COMPLETE_BLOCK = auto()
12:     CONTINUE = auto()
13:     VALIDATE = auto()
14:     FAIL = auto()
15: 
16: 
17: class ContextLossAction(Enum):
18:     RESTART_BLOCK = auto()
19:     FAIL = auto()
20: 
21: 
22: @dataclass(frozen=True, init=False)
23: class CommandSpec:
24:     line: str
25:     completion_states: tuple = ()
26:     capture_output: bool = False
27:     suppress_output: bool = False
28:     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK
29:     expected_completion_state: object = None
30:     fail_on_error: bool = False
31:     context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK
32:     continuation: bool = False
33: 
34:     def __init__(self, line, completion_states=(), capture_output=False,
35:                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,
36:                  expected_completion_state=None, fail_on_error=False,
37:                  context_loss=None, continuation=False):
38:         object.__setattr__(self, "line", line)
39:         object.__setattr__(self, "completion_states", completion_states)
40:         object.__setattr__(self, "capture_output", capture_output)
41:         object.__setattr__(self, "suppress_output", suppress_output)
42:         object.__setattr__(self, "session_loss", session_loss)
43:         object.__setattr__(self, "expected_completion_state", expected_completion_state)
44:         object.__setattr__(self, "fail_on_error", fail_on_error)
45:         object.__setattr__(self, "continuation", continuation)
46:         if context_loss is None:
47:             # Commands that must not replay after logout must not replay after
48:             # an unexpected scope exit either. Features can override this policy.
49:             context_loss = (
50:                 ContextLossAction.RESTART_BLOCK
51:                 if session_loss == SessionLossAction.RESTART_BLOCK
52:                 else ContextLossAction.FAIL
53:             )
54:         object.__setattr__(self, "context_loss", context_loss)
55:         self.__post_init__()
56: 
57:     def __post_init__(self):
58:         if "\r" in self.line or "\n" in self.line:
59:             raise ValueError("CLI commands must contain exactly one line")
60: 
61:     @property
62:     def closes_scope(self):
63:         return not self.continuation and self.line.strip().lower() in {"next", "end"}
64: 
65: 
66: @dataclass
67: class CommandAttempt:
68:     spec: CommandSpec
69:     number: int
70:     session_epoch: int
71:     output: bytearray = field(default_factory=bytearray)
72:     prompt_context_before: tuple | None = None
73:     prompt_context_after: tuple | None = None
74:     block_index: int | None = None
75:     retry_count: int = 0
76: 
77:     def on_output(self, output):
78:         if not (self.spec.capture_output or self.spec.closes_scope):
79:             return False
80:         data = bytes(output)
81:         self.output.extend(data)
82:         output.discard(data)
83:         return True
84: 
85: 
86: class Scope:
87:     def __init__(self, value, children=()):
88:         self.value = value
89:         self.children = list(children)
90: 
91:     @property
92:     def open_line(self):
93:         raise NotImplementedError
94: 
95:     @property
96:     def close_line(self):
97:         raise NotImplementedError
98: 
99:     def flatten(self):
100:         commands = flatten_commands(self.open_line)
101:         for child in self.children:
102:             commands.extend(flatten_commands(child))
103:         commands.append(CommandSpec(self.close_line))
104:         return commands
105: 
106: 
107: class ConfigBlock(Scope):
108:     @property
109:     def open_line(self):
110:         return f"config {self.value}"
111: 
112:     @property
113:     def close_line(self):
114:         return "end"
115: 
116: 
117: class EditBlock(Scope):
118:     @property
119:     def open_line(self):
120:         return f"edit {self.value}"
121: 
122:     @property
123:     def close_line(self):
124:         return "next"
125: 
126: 
127: class SetValue:
128:     """A quoted ``set`` command supporting FortiOS continuation prompts."""
129: 
130:     def __init__(self, field, value, fail_on_error=True, validate_prompt=True):
131:         self.field = field
132:         self.value = value
133:         self.fail_on_error = fail_on_error
134:         self.validate_prompt = validate_prompt
135: 
136:     def flatten(self):
137:         lines = str(self.value).strip().splitlines() or [""]
138:         lines[0] = f'set {self.field} "{lines[0]}'
139:         lines[-1] += '"'
140:         return _flatten_quoted_lines(
141:             lines, fail_on_error=self.fail_on_error,
142:             validate_prompt=self.validate_prompt,
143:         )
144: 
145: 
146: def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):
147:     """Send a logical command one line per continuation prompt, without re-quoting."""
148:     commands = []
149:     for index, line in enumerate(lines):
150:         last_line = index == len(lines) - 1
151:         expected = (
152:             FOSCliState.CMD_PROMPT if last_line
153:             else FOSCliState.MULTILINE_PROMPT
154:         )
155:         completion_states = ()
156:         if len(lines) > 1:
157:             completion_states = (
158:                 (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)
159:                 if last_line else
160:                 (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
161:             )
162:         commands.append(CommandSpec(
163:             line,
164:             completion_states=completion_states,
165:             capture_output=True,
166:             expected_completion_state=expected if validate_prompt else None,
167:             fail_on_error=fail_on_error,
168:             continuation=index > 0,
169:         ))
170:     return commands
171: 
172: 
173: class CommandSequence:
174:     """An unscoped workflow container; it does not emit CLI framing."""
175: 
176:     def __init__(self, name, children=()):
177:         self.name = name
178:         self.children = list(children)
179: 
180:     def flatten(self):
181:         commands = []
182:         for child in self.children:
183:             commands.extend(flatten_commands(child))
184:         return commands
185: 
186: 
187: def flatten_commands(value):
188:     """Flatten command containers and wrap plain CLI lines with defaults."""
189:     if isinstance(value, str):
190:         if "\n" in value:
191:             return _flatten_quoted_lines(value.split("\n"))
192:         return [CommandSpec(value)]
193:     if isinstance(value, CommandSpec):
194:         return [value]
195:     if isinstance(value, (Scope, CommandSequence, SetValue)):
196:         return value.flatten()
197:     raise TypeError(
198:         "Commands must be strings, CommandSpec instances, or command containers"
199:     )
200: 
201: 
202: @dataclass(frozen=True)
203: class CleanupAction:
204:     name: str
205:     block: object
206:     on_completion: bool = True
207:     on_interruption: bool = True

(End of file - total 207 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d431ff0011Wv7wLcbzhtfw5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3df9a001Z6KRG0YbSMbHXs",
  "callID": "call_1ec2f57027e44ea58ccbf7fa",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/cli_commands.py"
    },
    "output": "<path>/source/head/fortinet/common/cli_commands.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n2: \n3: from dataclasses import dataclass, field\n4: from enum import Enum, auto\n5: \n6: from .common import FOSCliState\n7: \n8: \n9: class SessionLossAction(Enum):\n10:     RESTART_BLOCK = auto()\n11:     COMPLETE_BLOCK = auto()\n12:     CONTINUE = auto()\n13:     VALIDATE = auto()\n14:     FAIL = auto()\n15: \n16: \n17: class ContextLossAction(Enum):\n18:     RESTART_BLOCK = auto()\n19:     FAIL = auto()\n20: \n21: \n22: @dataclass(frozen=True, init=False)\n23: class CommandSpec:\n24:     line: str\n25:     completion_states: tuple = ()\n26:     capture_output: bool = False\n27:     suppress_output: bool = False\n28:     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n29:     expected_completion_state: object = None\n30:     fail_on_error: bool = False\n31:     context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n32:     continuation: bool = False\n33: \n34:     def __init__(self, line, completion_states=(), capture_output=False,\n35:                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n36:                  expected_completion_state=None, fail_on_error=False,\n37:                  context_loss=None, continuation=False):\n38:         object.__setattr__(self, \"line\", line)\n39:         object.__setattr__(self, \"completion_states\", completion_states)\n40:         object.__setattr__(self, \"capture_output\", capture_output)\n41:         object.__setattr__(self, \"suppress_output\", suppress_output)\n42:         object.__setattr__(self, \"session_loss\", session_loss)\n43:         object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n44:         object.__setattr__(self, \"fail_on_error\", fail_on_error)\n45:         object.__setattr__(self, \"continuation\", continuation)\n46:         if context_loss is None:\n47:             # Commands that must not replay after logout must not replay after\n48:             # an unexpected scope exit either. Features can override this policy.\n49:             context_loss = (\n50:                 ContextLossAction.RESTART_BLOCK\n51:                 if session_loss == SessionLossAction.RESTART_BLOCK\n52:                 else ContextLossAction.FAIL\n53:             )\n54:         object.__setattr__(self, \"context_loss\", context_loss)\n55:         self.__post_init__()\n56: \n57:     def __post_init__(self):\n58:         if \"\\r\" in self.line or \"\\n\" in self.line:\n59:             raise ValueError(\"CLI commands must contain exactly one line\")\n60: \n61:     @property\n62:     def closes_scope(self):\n63:         return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n64: \n65: \n66: @dataclass\n67: class CommandAttempt:\n68:     spec: CommandSpec\n69:     number: int\n70:     session_epoch: int\n71:     output: bytearray = field(default_factory=bytearray)\n72:     prompt_context_before: tuple | None = None\n73:     prompt_context_after: tuple | None = None\n74:     block_index: int | None = None\n75:     retry_count: int = 0\n76: \n77:     def on_output(self, output):\n78:         if not (self.spec.capture_output or self.spec.closes_scope):\n79:             return False\n80:         data = bytes(output)\n81:         self.output.extend(data)\n82:         output.discard(data)\n83:         return True\n84: \n85: \n86: class Scope:\n87:     def __init__(self, value, children=()):\n88:         self.value = value\n89:         self.children = list(children)\n90: \n91:     @property\n92:     def open_line(self):\n93:         raise NotImplementedError\n94: \n95:     @property\n96:     def close_line(self):\n97:         raise NotImplementedError\n98: \n99:     def flatten(self):\n100:         commands = flatten_commands(self.open_line)\n101:         for child in self.children:\n102:             commands.extend(flatten_commands(child))\n103:         commands.append(CommandSpec(self.close_line))\n104:         return commands\n105: \n106: \n107: class ConfigBlock(Scope):\n108:     @property\n109:     def open_line(self):\n110:         return f\"config {self.value}\"\n111: \n112:     @property\n113:     def close_line(self):\n114:         return \"end\"\n115: \n116: \n117: class EditBlock(Scope):\n118:     @property\n119:     def open_line(self):\n120:         return f\"edit {self.value}\"\n121: \n122:     @property\n123:     def close_line(self):\n124:         return \"next\"\n125: \n126: \n127: class SetValue:\n128:     \"\"\"A quoted ``set`` command supporting FortiOS continuation prompts.\"\"\"\n129: \n130:     def __init__(self, field, value, fail_on_error=True, validate_prompt=True):\n131:         self.field = field\n132:         self.value = value\n133:         self.fail_on_error = fail_on_error\n134:         self.validate_prompt = validate_prompt\n135: \n136:     def flatten(self):\n137:         lines = str(self.value).strip().splitlines() or [\"\"]\n138:         lines[0] = f'set {self.field} \"{lines[0]}'\n139:         lines[-1] += '\"'\n140:         return _flatten_quoted_lines(\n141:             lines, fail_on_error=self.fail_on_error,\n142:             validate_prompt=self.validate_prompt,\n143:         )\n144: \n145: \n146: def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n147:     \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n148:     commands = []\n149:     for index, line in enumerate(lines):\n150:         last_line = index == len(lines) - 1\n151:         expected = (\n152:             FOSCliState.CMD_PROMPT if last_line\n153:             else FOSCliState.MULTILINE_PROMPT\n154:         )\n155:         completion_states = ()\n156:         if len(lines) > 1:\n157:             completion_states = (\n158:                 (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n159:                 if last_line else\n160:                 (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n161:             )\n162:         commands.append(CommandSpec(\n163:             line,\n164:             completion_states=completion_states,\n165:             capture_output=True,\n166:             expected_completion_state=expected if validate_prompt else None,\n167:             fail_on_error=fail_on_error,\n168:             continuation=index > 0,\n169:         ))\n170:     return commands\n171: \n172: \n173: class CommandSequence:\n174:     \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n175: \n176:     def __init__(self, name, children=()):\n177:         self.name = name\n178:         self.children = list(children)\n179: \n180:     def flatten(self):\n181:         commands = []\n182:         for child in self.children:\n183:             commands.extend(flatten_commands(child))\n184:         return commands\n185: \n186: \n187: def flatten_commands(value):\n188:     \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n189:     if isinstance(value, str):\n190:         if \"\\n\" in value:\n191:             return _flatten_quoted_lines(value.split(\"\\n\"))\n192:         return [CommandSpec(value)]\n193:     if isinstance(value, CommandSpec):\n194:         return [value]\n195:     if isinstance(value, (Scope, CommandSequence, SetValue)):\n196:         return value.flatten()\n197:     raise TypeError(\n198:         \"Commands must be strings, CommandSpec instances, or command containers\"\n199:     )\n200: \n201: \n202: @dataclass(frozen=True)\n203: class CleanupAction:\n204:     name: str\n205:     block: object\n206:     on_completion: bool = True\n207:     on_interruption: bool = True\n\n(End of file - total 207 lines)\n</content>",
    "title": "source/head/fortinet/common/cli_commands.py",
    "metadata": {
      "preview": "\"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\n\nfrom .common import FOSCliState\n\n\nclass SessionLossAction(Enum):\n    RESTART_BLOCK = auto()\n    COMPLETE_BLOCK = auto()\n    CONTINUE = auto()\n    VALIDATE = auto()\n    FAIL = auto()\n\n\nclass ContextLossAction(Enum):\n    RESTART_BLOCK = auto()\n    FAIL = auto()\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/cli_commands.py",
        "text": "\"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\n\nfrom .common import FOSCliState\n\n\nclass SessionLossAction(Enum):\n    RESTART_BLOCK = auto()\n    COMPLETE_BLOCK = auto()\n    CONTINUE = auto()\n    VALIDATE = auto()\n    FAIL = auto()\n\n\nclass ContextLossAction(Enum):\n    RESTART_BLOCK = auto()\n    FAIL = auto()\n\n\n@dataclass(frozen=True, init=False)\nclass CommandSpec:\n    line: str\n    completion_states: tuple = ()\n    capture_output: bool = False\n    suppress_output: bool = False\n    session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n    expected_completion_state: object = None\n    fail_on_error: bool = False\n    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n    continuation: bool = False\n\n    def __init__(self, line, completion_states=(), capture_output=False,\n                 suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n                 expected_completion_state=None, fail_on_error=False,\n                 context_loss=None, continuation=False):\n        object.__setattr__(self, \"line\", line)\n        object.__setattr__(self, \"completion_states\", completion_states)\n        object.__setattr__(self, \"capture_output\", capture_output)\n        object.__setattr__(self, \"suppress_output\", suppress_output)\n        object.__setattr__(self, \"session_loss\", session_loss)\n        object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n        object.__setattr__(self, \"fail_on_error\", fail_on_error)\n        object.__setattr__(self, \"continuation\", continuation)\n        if context_loss is None:\n            # Commands that must not replay after logout must not replay after\n            # an unexpected scope exit either. Features can override this policy.\n            context_loss = (\n                ContextLossAction.RESTART_BLOCK\n                if session_loss == SessionLossAction.RESTART_BLOCK\n                else ContextLossAction.FAIL\n            )\n        object.__setattr__(self, \"context_loss\", context_loss)\n        self.__post_init__()\n\n    def __post_init__(self):\n        if \"\\r\" in self.line or \"\\n\" in self.line:\n            raise ValueError(\"CLI commands must contain exactly one line\")\n\n    @property\n    def closes_scope(self):\n        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n\n\n@dataclass\nclass CommandAttempt:\n    spec: CommandSpec\n    number: int\n    session_epoch: int\n    output: bytearray = field(default_factory=bytearray)\n    prompt_context_before: tuple | None = None\n    prompt_context_after: tuple | None = None\n    block_index: int | None = None\n    retry_count: int = 0\n\n    def on_output(self, output):\n        if not (self.spec.capture_output or self.spec.closes_scope):\n            return False\n        data = bytes(output)\n        self.output.extend(data)\n        output.discard(data)\n        return True\n\n\nclass Scope:\n    def __init__(self, value, children=()):\n        self.value = value\n        self.children = list(children)\n\n    @property\n    def open_line(self):\n        raise NotImplementedError\n\n    @property\n    def close_line(self):\n        raise NotImplementedError\n\n    def flatten(self):\n        commands = flatten_commands(self.open_line)\n        for child in self.children:\n            commands.extend(flatten_commands(child))\n        commands.append(CommandSpec(self.close_line))\n        return commands\n\n\nclass ConfigBlock(Scope):\n    @property\n    def open_line(self):\n        return f\"config {self.value}\"\n\n    @property\n    def close_line(self):\n        return \"end\"\n\n\nclass EditBlock(Scope):\n    @property\n    def open_line(self):\n        return f\"edit {self.value}\"\n\n    @property\n    def close_line(self):\n        return \"next\"\n\n\nclass SetValue:\n    \"\"\"A quoted ``set`` command supporting FortiOS continuation prompts.\"\"\"\n\n    def __init__(self, field, value, fail_on_error=True, validate_prompt=True):\n        self.field = field\n        self.value = value\n        self.fail_on_error = fail_on_error\n        self.validate_prompt = validate_prompt\n\n    def flatten(self):\n        lines = str(self.value).strip().splitlines() or [\"\"]\n        lines[0] = f'set {self.field} \"{lines[0]}'\n        lines[-1] += '\"'\n        return _flatten_quoted_lines(\n            lines, fail_on_error=self.fail_on_error,\n            validate_prompt=self.validate_prompt,\n        )\n\n\ndef _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n    commands = []\n    for index, line in enumerate(lines):\n        last_line = index == len(lines) - 1\n        expected = (\n            FOSCliState.CMD_PROMPT if last_line\n            else FOSCliState.MULTILINE_PROMPT\n        )\n        completion_states = ()\n        if len(lines) > 1:\n            completion_states = (\n                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n                if last_line else\n                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n            )\n        commands.append(CommandSpec(\n            line,\n            completion_states=completion_states,\n            capture_output=True,\n            expected_completion_state=expected if validate_prompt else None,\n            fail_on_error=fail_on_error,\n            continuation=index > 0,\n        ))\n    return commands\n\n\nclass CommandSequence:\n    \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n\n    def __init__(self, name, children=()):\n        self.name = name\n        self.children = list(children)\n\n    def flatten(self):\n        commands = []\n        for child in self.children:\n            commands.extend(flatten_commands(child))\n        return commands\n\n\ndef flatten_commands(value):\n    \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n    if isinstance(value, str):\n        if \"\\n\" in value:\n            return _flatten_quoted_lines(value.split(\"\\n\"))\n        return [CommandSpec(value)]\n    if isinstance(value, CommandSpec):\n        return [value]\n    if isinstance(value, (Scope, CommandSequence, SetValue)):\n        return value.flatten()\n    raise TypeError(\n        \"Commands must be strings, CommandSpec instances, or command containers\"\n    )\n\n\n@dataclass(frozen=True)\nclass CleanupAction:\n    name: str\n    block: object\n    on_completion: bool = True\n    on_interruption: bool = True",
        "lineStart": 1,
        "lineEnd": 207,
        "totalLines": 207,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716400643,
      "end": 1793716400649
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_cli_driver.py"
}

Output

<path>/source/head/fortinet/common/fos_cli_driver.py</path>
<type>file</type>
<content>
1: import logging
2: import re
3: import time
4: from .common import (
5:     FOSCliState,
6:     FOS_CLI_STATE_PATTERNS,
7:     BOOTSTRAP_HOSTNAME_REGEX,
8:     PROMPT_CONTEXT_REGEX,
9:     TRACE_LEVEL,
10: )
11: 
12: 
13: PROCESS_SPIN_SECONDS = 10
14: EXPECT_TIMEOUT_SECONDS = 1
15: UNKNOWN_STALL_SECONDS = 30
16: UNKNOWN_STALL_NEWLINE_LIMIT = 3
17: 
18: 
19: class KernelPanicError(RuntimeError):
20:     """Raised when the guest kernel reports a panic on the serial console."""
21: 
22: 
23: class FOSCliDriver:
24:     """Owns serial reads and delegates command dispatch to the commander."""
25: 
26:     def __init__(
27:         self,
28:         terminal,
29:         commander,
30:         credentials,
31:         logger,
32:         bootstrap_password,
33:         activate_blank_credentials,
34:         activate_bootstrap_credentials,
35:         allow_credential_recovery=False,
36:     ):
37:         self._terminal = terminal
38:         self._commander = commander
39:         self._logger = logger
40:         self._state_patterns = FOS_CLI_STATE_PATTERNS.copy()
41:         self._last_known_state = FOSCliState.UNKNOWN
42:         self._current_state = FOSCliState.UNKNOWN
43:         self._last_logged_state = None
44:         self._idle_spins = 0
45:         self._credentials = credentials
46:         self._bootstrap_password = bootstrap_password
47:         self._activate_blank_credentials = activate_blank_credentials
48:         self._activate_bootstrap_credentials = activate_bootstrap_credentials
49:         self._allow_credential_recovery = allow_credential_recovery
50:         self._recovery_credentials = None
51:         self._recovery_attempted = False
52:         self._use_recovery_credentials = False
53:         self._blank_fallback_available = True
54:         self._send_blank_password = False
55:         self._initial_login_complete = False
56:         self._awaiting_login_acceptance = False
57:         self._credential_recovery_pending = False
58:         self._pending_bootstrap_activation = False
59:         self._unknown_started_at = None
60:         self._unknown_newlines = 0
61:         self._state_handlers = {
62:             FOSCliState.PROVIDE_USERNAME: self._provide_username,
63:             FOSCliState.PROVIDE_PASSWORD: self._provide_password,
64:             FOSCliState.CURRENT_PASSWORD: self._provide_current_password,
65:             FOSCliState.CHANGE_PASSWORD: self._provide_new_password,
66:             FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,
67:             FOSCliState.MORE_PROMPT: self._continue_pager,
68:             FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,
69:             FOSCliState.CMD_PROMPT: self._command_prompt,
70:             FOSCliState.CMD_PROMPT_ECHO: None,
71:             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,
72:             FOSCliState.LIC_FAIL: self._license_failed,
73:             FOSCliState.TN_TIMEOUT: self._timeout,
74:             FOSCliState.KERNEL_PANIC: self._kernel_panic,
75:             FOSCliState.UNKNOWN: self._unknown,
76:         }
77: 
78:     @property
79:     def state_patterns(self):
80:         return self._state_patterns
81: 
82:     @property
83:     def ready(self):
84:         return self._commander.ready
85: 
86:     def remember_current_credentials(self):
87:         """Keep the last accepted credentials for a failed password transition."""
88:         if self._recovery_credentials is not None or self._recovery_attempted:
89:             return
90:         self._recovery_credentials = (
91:             self._credentials.username,
92:             self._credentials.password,
93:         )
94:         self._recovery_attempted = False
95: 
96:     @property
97:     def at_command_prompt(self):
98:         """Whether the most recent console event left FortiOS at a CLI prompt."""
99:         return self._current_state == FOSCliState.CMD_PROMPT or (
100:             self._current_state == FOSCliState.TN_TIMEOUT
101:             and self._last_known_state == FOSCliState.CMD_PROMPT
102:         )
103: 
104:     def process_state(self):
105:         spin_start = time.time()
106:         while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:
107:             state, output, matched = self._next_state()
108:             self._current_state = state
109:             if output and not matched:
110:                 self._commander.on_output(output)
111:                 if state == FOSCliState.UNKNOWN:
112:                     self._note_unknown_output()
113:                 output = type(output)(b"")
114:             if state.value < FOSCliState.UNKNOWN.value:
115:                 self._idle_spins = 0
116:                 self._last_known_state = state
117:                 self._clear_unknown_stall()
118:                 self._log_state(state)
119:             self._process_state(state, output)
120: 
121:     def _log_state(self, state):
122:         if state == FOSCliState.MULTILINE_PROMPT:
123:             return
124:         if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:
125:             return
126:         self._last_logged_state = state
127:         self._logger.debug(f"ST: {state.name}")
128: 
129:     def _process_state(self, state, output):
130:         """Handle a CLI state and then let the commander observe it.
131: 
132:         A password confirmation can be followed immediately by a command
133:         prompt, without ``Welcome!``.  Apply that credential transition
134:         before the commander dispatches the command associated with the
135:         prompt.
136:         """
137:         if state == FOSCliState.CMD_PROMPT:
138:             self._handle_state(state)
139:         if state == FOSCliState.CMD_PROMPT_ECHO:
140:             self._commander.on_prompt_echo(output)
141:         else:
142:             self._commander.on_state(state, output)
143:         if state != FOSCliState.CMD_PROMPT:
144:             self._handle_state(state)
145:         if state == FOSCliState.CMD_PROMPT:
146:             self._commander.tick()
147:         elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:
148:             self._commander.tick()
149:             self._commander.on_idle_prompt()
150: 
151:     def _next_state(self):
152:         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)
153:         if match:
154:             return FOSCliState(index), output, True
155:         # A timeout exposes retained bytes too. Only fresh input should reset
156:         # the unknown-output stall timer; an unchanged buffer is still idle.
157:         state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT
158:         return state, output, False
159: 
160:     def _handle_state(self, state):
161:         handler = self._state_handlers.get(state)
162:         if handler:
163:             try:
164:                 handler()
165:             except Exception:
166:                 self._logger.exception("CLI state handler failed for %s", state.name)
167:                 raise
168: 
169:     def _provide_username(self):
170:         username = self._credentials.username
171:         if self._use_recovery_credentials and self._recovery_credentials is not None:
172:             username = self._recovery_credentials[0]
173:         self._awaiting_login_acceptance = True
174:         self._respond(FOSCliState.PROVIDE_USERNAME, username)
175: 
176:     def _provide_password(self):
177:         if self._send_blank_password:
178:             # The initial blank-password fallback is consumed as soon as it is
179:             # sent. Later credential recovery is managed separately.
180:             self._send_blank_password = False
181:             self._blank_fallback_available = False
182:             self._activate_blank_credentials()
183:             self._respond(FOSCliState.PROVIDE_PASSWORD, b"")
184:             return
185:         if self._use_recovery_credentials and self._recovery_credentials is not None:
186:             self._respond(
187:                 FOSCliState.PROVIDE_PASSWORD,
188:                 self._recovery_credentials[1],
189:             )
190:             return
191:         self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)
192: 
193:     def _provide_current_password(self):
194:         self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)
195: 
196:     def _provide_new_password(self):
197:         self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)
198: 
199:     def _confirm_new_password(self):
200:         self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)
201:         # Do not update active credentials until FortiOS accepts the
202:         # confirmation. A rejected confirmation leaves the active password
203:         # unchanged so that subsequent prompts use the right value.
204:         self._pending_bootstrap_activation = True
205: 
206:     def _continue_pager(self):
207:         self._terminal.write(b" ")
208: 
209:     def _credential_accepted(self):
210:         self._accept_login()
211: 
212:     def _accept_login(self):
213:         self._initial_login_complete = True
214:         self._awaiting_login_acceptance = False
215:         recovered = (
216:             self._use_recovery_credentials
217:             and self._recovery_credentials is not None
218:         )
219:         if recovered:
220:             self._use_recovery_credentials = False
221:             self._recovery_attempted = False
222:             if not self._credential_recovery_pending:
223:                 self._commander.record_feature_error(
224:                     "admin-credentials",
225:                     "desired credentials were rejected; resumed with the previous credentials "
226:                     "while keeping the desired credentials for later logins",
227:                 )
228:             self._credential_recovery_pending = True
229:         elif self._recovery_credentials is not None:
230:             self._recovery_attempted = False
231:             if self._credential_recovery_pending:
232:                 self._commander.resolve_feature_error(
233:                     "admin-credentials",
234:                     "the desired credentials authenticated successfully",
235:                 )
236:                 self._credential_recovery_pending = False
237:         self._activate_pending_bootstrap_credentials()
238: 
239:     def _command_prompt(self):
240:         """Accept password confirmation on versions that skip ``Welcome!``."""
241:         if self._awaiting_login_acceptance:
242:             self._accept_login()
243:         else:
244:             self._initial_login_complete = True
245:             self._activate_pending_bootstrap_credentials()
246: 
247:     def _activate_pending_bootstrap_credentials(self):
248:         if self._pending_bootstrap_activation:
249:             self._activate_bootstrap_credentials()
250:             self._pending_bootstrap_activation = False
251: 
252:     @staticmethod
253:     def _license_failed():
254:         # SetLicense inspects the buffered command output when FortiOS returns
255:         # to a prompt. Raising here would interrupt the driver at LIC_FAIL,
256:         # before best-effort bootstrap can safely skip the feature.
257:         return None
258: 
259:     def _timeout(self):
260:         self._idle_spins += 1
261:         self._recover_unknown_stall()
262: 
263:     def _unknown(self):
264:         if self._last_known_state == FOSCliState.REBOOTING:
265:             self._idle_spins += 1
266: 
267:     @staticmethod
268:     def _kernel_panic():
269:         raise KernelPanicError("Kernel panic detected on serial console")
270: 
271:     def _note_unknown_output(self):
272:         self._unknown_started_at = time.monotonic()
273: 
274:     def _recover_unknown_stall(self):
275:         if self._unknown_started_at is None:
276:             return
277:         if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:
278:             return
279:         if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:
280:             raise RuntimeError("CLI remained in unknown state")
281:         self._unknown_newlines += 1
282:         self._unknown_started_at = time.monotonic()
283:         self._logger.warning(
284:             "CLI stuck in unknown state; sending newline "
285:             f"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})"
286:         )
287:         self._terminal.write(b"\r")
288: 
289:     def _clear_unknown_stall(self):
290:         self._unknown_started_at = None
291:         self._unknown_newlines = 0
292: 
293:     def set_prompt_patterns(self, name_pattern):
294:         if isinstance(name_pattern, str):
295:             name_pattern = re.escape(name_pattern.encode())
296:         self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb"(?m)^[ \t]*" + name_pattern + rb"[ \t]+login:[ \t]*"
297:         self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*\r?$"
298:         self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*[^\r\n]+(?:\r?\n)?"
299: 
300:     def _credential_rejected(self):
301:         # A rejected interaction cannot establish the newly selected
302:         # bootstrap password.  Do not activate it on a later unrelated
303:         # acceptance or prompt.
304:         self._pending_bootstrap_activation = False
305:         if not self._initial_login_complete and self._blank_fallback_available:
306:             self._send_blank_password = True
307:             return
308:         if (
309:             self._allow_credential_recovery
310:             and self._recovery_credentials is not None
311:             and not self._recovery_attempted
312:         ):
313:             self._recovery_attempted = True
314:             self._use_recovery_credentials = True
315:             self._logger.warning(
316:                 "Credentials were rejected; retrying with the previously accepted credentials"
317:             )
318:             return
319:         raise RuntimeError("Credential rejected")
320: 
321:     def _respond(self, state, response):
322:         """Write an interactive response to the CLI."""
323:         if isinstance(response, str):
324:             response = response.encode()
325:         self._logger.log(
326:             TRACE_LEVEL,
327:             "Responding to CLI state %s with '%s'",
328:             state.name,
329:             response,
330:         )
331:         self._terminal.write(bytes(response) + b"\r")

(End of file - total 331 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d43242001onoTkvOFr4XoLB",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3df9a001Z6KRG0YbSMbHXs",
  "callID": "call_2e9adc497748473aa0b3795e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_cli_driver.py"
    },
    "output": "<path>/source/head/fortinet/common/fos_cli_driver.py</path>\n<type>file</type>\n<content>\n1: import logging\n2: import re\n3: import time\n4: from .common import (\n5:     FOSCliState,\n6:     FOS_CLI_STATE_PATTERNS,\n7:     BOOTSTRAP_HOSTNAME_REGEX,\n8:     PROMPT_CONTEXT_REGEX,\n9:     TRACE_LEVEL,\n10: )\n11: \n12: \n13: PROCESS_SPIN_SECONDS = 10\n14: EXPECT_TIMEOUT_SECONDS = 1\n15: UNKNOWN_STALL_SECONDS = 30\n16: UNKNOWN_STALL_NEWLINE_LIMIT = 3\n17: \n18: \n19: class KernelPanicError(RuntimeError):\n20:     \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n21: \n22: \n23: class FOSCliDriver:\n24:     \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n25: \n26:     def __init__(\n27:         self,\n28:         terminal,\n29:         commander,\n30:         credentials,\n31:         logger,\n32:         bootstrap_password,\n33:         activate_blank_credentials,\n34:         activate_bootstrap_credentials,\n35:         allow_credential_recovery=False,\n36:     ):\n37:         self._terminal = terminal\n38:         self._commander = commander\n39:         self._logger = logger\n40:         self._state_patterns = FOS_CLI_STATE_PATTERNS.copy()\n41:         self._last_known_state = FOSCliState.UNKNOWN\n42:         self._current_state = FOSCliState.UNKNOWN\n43:         self._last_logged_state = None\n44:         self._idle_spins = 0\n45:         self._credentials = credentials\n46:         self._bootstrap_password = bootstrap_password\n47:         self._activate_blank_credentials = activate_blank_credentials\n48:         self._activate_bootstrap_credentials = activate_bootstrap_credentials\n49:         self._allow_credential_recovery = allow_credential_recovery\n50:         self._recovery_credentials = None\n51:         self._recovery_attempted = False\n52:         self._use_recovery_credentials = False\n53:         self._blank_fallback_available = True\n54:         self._send_blank_password = False\n55:         self._initial_login_complete = False\n56:         self._awaiting_login_acceptance = False\n57:         self._credential_recovery_pending = False\n58:         self._pending_bootstrap_activation = False\n59:         self._unknown_started_at = None\n60:         self._unknown_newlines = 0\n61:         self._state_handlers = {\n62:             FOSCliState.PROVIDE_USERNAME: self._provide_username,\n63:             FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n64:             FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n65:             FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n66:             FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n67:             FOSCliState.MORE_PROMPT: self._continue_pager,\n68:             FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n69:             FOSCliState.CMD_PROMPT: self._command_prompt,\n70:             FOSCliState.CMD_PROMPT_ECHO: None,\n71:             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n72:             FOSCliState.LIC_FAIL: self._license_failed,\n73:             FOSCliState.TN_TIMEOUT: self._timeout,\n74:             FOSCliState.KERNEL_PANIC: self._kernel_panic,\n75:             FOSCliState.UNKNOWN: self._unknown,\n76:         }\n77: \n78:     @property\n79:     def state_patterns(self):\n80:         return self._state_patterns\n81: \n82:     @property\n83:     def ready(self):\n84:         return self._commander.ready\n85: \n86:     def remember_current_credentials(self):\n87:         \"\"\"Keep the last accepted credentials for a failed password transition.\"\"\"\n88:         if self._recovery_credentials is not None or self._recovery_attempted:\n89:             return\n90:         self._recovery_credentials = (\n91:             self._credentials.username,\n92:             self._credentials.password,\n93:         )\n94:         self._recovery_attempted = False\n95: \n96:     @property\n97:     def at_command_prompt(self):\n98:         \"\"\"Whether the most recent console event left FortiOS at a CLI prompt.\"\"\"\n99:         return self._current_state == FOSCliState.CMD_PROMPT or (\n100:             self._current_state == FOSCliState.TN_TIMEOUT\n101:             and self._last_known_state == FOSCliState.CMD_PROMPT\n102:         )\n103: \n104:     def process_state(self):\n105:         spin_start = time.time()\n106:         while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:\n107:             state, output, matched = self._next_state()\n108:             self._current_state = state\n109:             if output and not matched:\n110:                 self._commander.on_output(output)\n111:                 if state == FOSCliState.UNKNOWN:\n112:                     self._note_unknown_output()\n113:                 output = type(output)(b\"\")\n114:             if state.value < FOSCliState.UNKNOWN.value:\n115:                 self._idle_spins = 0\n116:                 self._last_known_state = state\n117:                 self._clear_unknown_stall()\n118:                 self._log_state(state)\n119:             self._process_state(state, output)\n120: \n121:     def _log_state(self, state):\n122:         if state == FOSCliState.MULTILINE_PROMPT:\n123:             return\n124:         if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:\n125:             return\n126:         self._last_logged_state = state\n127:         self._logger.debug(f\"ST: {state.name}\")\n128: \n129:     def _process_state(self, state, output):\n130:         \"\"\"Handle a CLI state and then let the commander observe it.\n131: \n132:         A password confirmation can be followed immediately by a command\n133:         prompt, without ``Welcome!``.  Apply that credential transition\n134:         before the commander dispatches the command associated with the\n135:         prompt.\n136:         \"\"\"\n137:         if state == FOSCliState.CMD_PROMPT:\n138:             self._handle_state(state)\n139:         if state == FOSCliState.CMD_PROMPT_ECHO:\n140:             self._commander.on_prompt_echo(output)\n141:         else:\n142:             self._commander.on_state(state, output)\n143:         if state != FOSCliState.CMD_PROMPT:\n144:             self._handle_state(state)\n145:         if state == FOSCliState.CMD_PROMPT:\n146:             self._commander.tick()\n147:         elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:\n148:             self._commander.tick()\n149:             self._commander.on_idle_prompt()\n150: \n151:     def _next_state(self):\n152:         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n153:         if match:\n154:             return FOSCliState(index), output, True\n155:         # A timeout exposes retained bytes too. Only fresh input should reset\n156:         # the unknown-output stall timer; an unchanged buffer is still idle.\n157:         state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n158:         return state, output, False\n159: \n160:     def _handle_state(self, state):\n161:         handler = self._state_handlers.get(state)\n162:         if handler:\n163:             try:\n164:                 handler()\n165:             except Exception:\n166:                 self._logger.exception(\"CLI state handler failed for %s\", state.name)\n167:                 raise\n168: \n169:     def _provide_username(self):\n170:         username = self._credentials.username\n171:         if self._use_recovery_credentials and self._recovery_credentials is not None:\n172:             username = self._recovery_credentials[0]\n173:         self._awaiting_login_acceptance = True\n174:         self._respond(FOSCliState.PROVIDE_USERNAME, username)\n175: \n176:     def _provide_password(self):\n177:         if self._send_blank_password:\n178:             # The initial blank-password fallback is consumed as soon as it is\n179:             # sent. Later credential recovery is managed separately.\n180:             self._send_blank_password = False\n181:             self._blank_fallback_available = False\n182:             self._activate_blank_credentials()\n183:             self._respond(FOSCliState.PROVIDE_PASSWORD, b\"\")\n184:             return\n185:         if self._use_recovery_credentials and self._recovery_credentials is not None:\n186:             self._respond(\n187:                 FOSCliState.PROVIDE_PASSWORD,\n188:                 self._recovery_credentials[1],\n189:             )\n190:             return\n191:         self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)\n192: \n193:     def _provide_current_password(self):\n194:         self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)\n195: \n196:     def _provide_new_password(self):\n197:         self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)\n198: \n199:     def _confirm_new_password(self):\n200:         self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)\n201:         # Do not update active credentials until FortiOS accepts the\n202:         # confirmation. A rejected confirmation leaves the active password\n203:         # unchanged so that subsequent prompts use the right value.\n204:         self._pending_bootstrap_activation = True\n205: \n206:     def _continue_pager(self):\n207:         self._terminal.write(b\" \")\n208: \n209:     def _credential_accepted(self):\n210:         self._accept_login()\n211: \n212:     def _accept_login(self):\n213:         self._initial_login_complete = True\n214:         self._awaiting_login_acceptance = False\n215:         recovered = (\n216:             self._use_recovery_credentials\n217:             and self._recovery_credentials is not None\n218:         )\n219:         if recovered:\n220:             self._use_recovery_credentials = False\n221:             self._recovery_attempted = False\n222:             if not self._credential_recovery_pending:\n223:                 self._commander.record_feature_error(\n224:                     \"admin-credentials\",\n225:                     \"desired credentials were rejected; resumed with the previous credentials \"\n226:                     \"while keeping the desired credentials for later logins\",\n227:                 )\n228:             self._credential_recovery_pending = True\n229:         elif self._recovery_credentials is not None:\n230:             self._recovery_attempted = False\n231:             if self._credential_recovery_pending:\n232:                 self._commander.resolve_feature_error(\n233:                     \"admin-credentials\",\n234:                     \"the desired credentials authenticated successfully\",\n235:                 )\n236:                 self._credential_recovery_pending = False\n237:         self._activate_pending_bootstrap_credentials()\n238: \n239:     def _command_prompt(self):\n240:         \"\"\"Accept password confirmation on versions that skip ``Welcome!``.\"\"\"\n241:         if self._awaiting_login_acceptance:\n242:             self._accept_login()\n243:         else:\n244:             self._initial_login_complete = True\n245:             self._activate_pending_bootstrap_credentials()\n246: \n247:     def _activate_pending_bootstrap_credentials(self):\n248:         if self._pending_bootstrap_activation:\n249:             self._activate_bootstrap_credentials()\n250:             self._pending_bootstrap_activation = False\n251: \n252:     @staticmethod\n253:     def _license_failed():\n254:         # SetLicense inspects the buffered command output when FortiOS returns\n255:         # to a prompt. Raising here would interrupt the driver at LIC_FAIL,\n256:         # before best-effort bootstrap can safely skip the feature.\n257:         return None\n258: \n259:     def _timeout(self):\n260:         self._idle_spins += 1\n261:         self._recover_unknown_stall()\n262: \n263:     def _unknown(self):\n264:         if self._last_known_state == FOSCliState.REBOOTING:\n265:             self._idle_spins += 1\n266: \n267:     @staticmethod\n268:     def _kernel_panic():\n269:         raise KernelPanicError(\"Kernel panic detected on serial console\")\n270: \n271:     def _note_unknown_output(self):\n272:         self._unknown_started_at = time.monotonic()\n273: \n274:     def _recover_unknown_stall(self):\n275:         if self._unknown_started_at is None:\n276:             return\n277:         if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:\n278:             return\n279:         if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:\n280:             raise RuntimeError(\"CLI remained in unknown state\")\n281:         self._unknown_newlines += 1\n282:         self._unknown_started_at = time.monotonic()\n283:         self._logger.warning(\n284:             \"CLI stuck in unknown state; sending newline \"\n285:             f\"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})\"\n286:         )\n287:         self._terminal.write(b\"\\r\")\n288: \n289:     def _clear_unknown_stall(self):\n290:         self._unknown_started_at = None\n291:         self._unknown_newlines = 0\n292: \n293:     def set_prompt_patterns(self, name_pattern):\n294:         if isinstance(name_pattern, str):\n295:             name_pattern = re.escape(name_pattern.encode())\n296:         self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb\"(?m)^[ \\t]*\" + name_pattern + rb\"[ \\t]+login:[ \\t]*\"\n297:         self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n298:         self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n299: \n300:     def _credential_rejected(self):\n301:         # A rejected interaction cannot establish the newly selected\n302:         # bootstrap password.  Do not activate it on a later unrelated\n303:         # acceptance or prompt.\n304:         self._pending_bootstrap_activation = False\n305:         if not self._initial_login_complete and self._blank_fallback_available:\n306:             self._send_blank_password = True\n307:             return\n308:         if (\n309:             self._allow_credential_recovery\n310:             and self._recovery_credentials is not None\n311:             and not self._recovery_attempted\n312:         ):\n313:             self._recovery_attempted = True\n314:             self._use_recovery_credentials = True\n315:             self._logger.warning(\n316:                 \"Credentials were rejected; retrying with the previously accepted credentials\"\n317:             )\n318:             return\n319:         raise RuntimeError(\"Credential rejected\")\n320: \n321:     def _respond(self, state, response):\n322:         \"\"\"Write an interactive response to the CLI.\"\"\"\n323:         if isinstance(response, str):\n324:             response = response.encode()\n325:         self._logger.log(\n326:             TRACE_LEVEL,\n327:             \"Responding to CLI state %s with '%s'\",\n328:             state.name,\n329:             response,\n330:         )\n331:         self._terminal.write(bytes(response) + b\"\\r\")\n\n(End of file - total 331 lines)\n</content>",
    "title": "source/head/fortinet/common/fos_cli_driver.py",
    "metadata": {
      "preview": "import logging\nimport re\nimport time\nfrom .common import (\n    FOSCliState,\n    FOS_CLI_STATE_PATTERNS,\n    BOOTSTRAP_HOSTNAME_REGEX,\n    PROMPT_CONTEXT_REGEX,\n    TRACE_LEVEL,\n)\n\n\nPROCESS_SPIN_SECONDS = 10\nEXPECT_TIMEOUT_SECONDS = 1\nUNKNOWN_STALL_SECONDS = 30\nUNKNOWN_STALL_NEWLINE_LIMIT = 3\n\n\nclass KernelPanicError(RuntimeError):\n    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_cli_driver.py",
        "text": "import logging\nimport re\nimport time\nfrom .common import (\n    FOSCliState,\n    FOS_CLI_STATE_PATTERNS,\n    BOOTSTRAP_HOSTNAME_REGEX,\n    PROMPT_CONTEXT_REGEX,\n    TRACE_LEVEL,\n)\n\n\nPROCESS_SPIN_SECONDS = 10\nEXPECT_TIMEOUT_SECONDS = 1\nUNKNOWN_STALL_SECONDS = 30\nUNKNOWN_STALL_NEWLINE_LIMIT = 3\n\n\nclass KernelPanicError(RuntimeError):\n    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n\n\nclass FOSCliDriver:\n    \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n\n    def __init__(\n        self,\n        terminal,\n        commander,\n        credentials,\n        logger,\n        bootstrap_password,\n        activate_blank_credentials,\n        activate_bootstrap_credentials,\n        allow_credential_recovery=False,\n    ):\n        self._terminal = terminal\n        self._commander = commander\n        self._logger = logger\n        self._state_patterns = FOS_CLI_STATE_PATTERNS.copy()\n        self._last_known_state = FOSCliState.UNKNOWN\n        self._current_state = FOSCliState.UNKNOWN\n        self._last_logged_state = None\n        self._idle_spins = 0\n        self._credentials = credentials\n        self._bootstrap_password = bootstrap_password\n        self._activate_blank_credentials = activate_blank_credentials\n        self._activate_bootstrap_credentials = activate_bootstrap_credentials\n        self._allow_credential_recovery = allow_credential_recovery\n        self._recovery_credentials = None\n        self._recovery_attempted = False\n        self._use_recovery_credentials = False\n        self._blank_fallback_available = True\n        self._send_blank_password = False\n        self._initial_login_complete = False\n        self._awaiting_login_acceptance = False\n        self._credential_recovery_pending = False\n        self._pending_bootstrap_activation = False\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n        self._state_handlers = {\n            FOSCliState.PROVIDE_USERNAME: self._provide_username,\n            FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n            FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n            FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n            FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n            FOSCliState.MORE_PROMPT: self._continue_pager,\n            FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n            FOSCliState.CMD_PROMPT: self._command_prompt,\n            FOSCliState.CMD_PROMPT_ECHO: None,\n            FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n            FOSCliState.LIC_FAIL: self._license_failed,\n            FOSCliState.TN_TIMEOUT: self._timeout,\n            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n            FOSCliState.UNKNOWN: self._unknown,\n        }\n\n    @property\n    def state_patterns(self):\n        return self._state_patterns\n\n    @property\n    def ready(self):\n        return self._commander.ready\n\n    def remember_current_credentials(self):\n        \"\"\"Keep the last accepted credentials for a failed password transition.\"\"\"\n        if self._recovery_credentials is not None or self._recovery_attempted:\n            return\n        self._recovery_credentials = (\n            self._credentials.username,\n            self._credentials.password,\n        )\n        self._recovery_attempted = False\n\n    @property\n    def at_command_prompt(self):\n        \"\"\"Whether the most recent console event left FortiOS at a CLI prompt.\"\"\"\n        return self._current_state == FOSCliState.CMD_PROMPT or (\n            self._current_state == FOSCliState.TN_TIMEOUT\n            and self._last_known_state == FOSCliState.CMD_PROMPT\n        )\n\n    def process_state(self):\n        spin_start = time.time()\n        while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:\n            state, output, matched = self._next_state()\n            self._current_state = state\n            if output and not matched:\n                self._commander.on_output(output)\n                if state == FOSCliState.UNKNOWN:\n                    self._note_unknown_output()\n                output = type(output)(b\"\")\n            if state.value < FOSCliState.UNKNOWN.value:\n                self._idle_spins = 0\n                self._last_known_state = state\n                self._clear_unknown_stall()\n                self._log_state(state)\n            self._process_state(state, output)\n\n    def _log_state(self, state):\n        if state == FOSCliState.MULTILINE_PROMPT:\n            return\n        if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:\n            return\n        self._last_logged_state = state\n        self._logger.debug(f\"ST: {state.name}\")\n\n    def _process_state(self, state, output):\n        \"\"\"Handle a CLI state and then let the commander observe it.\n\n        A password confirmation can be followed immediately by a command\n        prompt, without ``Welcome!``.  Apply that credential transition\n        before the commander dispatches the command associated with the\n        prompt.\n        \"\"\"\n        if state == FOSCliState.CMD_PROMPT:\n            self._handle_state(state)\n        if state == FOSCliState.CMD_PROMPT_ECHO:\n            self._commander.on_prompt_echo(output)\n        else:\n            self._commander.on_state(state, output)\n        if state != FOSCliState.CMD_PROMPT:\n            self._handle_state(state)\n        if state == FOSCliState.CMD_PROMPT:\n            self._commander.tick()\n        elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:\n            self._commander.tick()\n            self._commander.on_idle_prompt()\n\n    def _next_state(self):\n        index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n        if match:\n            return FOSCliState(index), output, True\n        # A timeout exposes retained bytes too. Only fresh input should reset\n        # the unknown-output stall timer; an unchanged buffer is still idle.\n        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n        return state, output, False\n\n    def _handle_state(self, state):\n        handler = self._state_handlers.get(state)\n        if handler:\n            try:\n                handler()\n            except Exception:\n                self._logger.exception(\"CLI state handler failed for %s\", state.name)\n                raise\n\n    def _provide_username(self):\n        username = self._credentials.username\n        if self._use_recovery_credentials and self._recovery_credentials is not None:\n            username = self._recovery_credentials[0]\n        self._awaiting_login_acceptance = True\n        self._respond(FOSCliState.PROVIDE_USERNAME, username)\n\n    def _provide_password(self):\n        if self._send_blank_password:\n            # The initial blank-password fallback is consumed as soon as it is\n            # sent. Later credential recovery is managed separately.\n            self._send_blank_password = False\n            self._blank_fallback_available = False\n            self._activate_blank_credentials()\n            self._respond(FOSCliState.PROVIDE_PASSWORD, b\"\")\n            return\n        if self._use_recovery_credentials and self._recovery_credentials is not None:\n            self._respond(\n                FOSCliState.PROVIDE_PASSWORD,\n                self._recovery_credentials[1],\n            )\n            return\n        self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)\n\n    def _provide_current_password(self):\n        self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)\n\n    def _provide_new_password(self):\n        self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)\n\n    def _confirm_new_password(self):\n        self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)\n        # Do not update active credentials until FortiOS accepts the\n        # confirmation. A rejected confirmation leaves the active password\n        # unchanged so that subsequent prompts use the right value.\n        self._pending_bootstrap_activation = True\n\n    def _continue_pager(self):\n        self._terminal.write(b\" \")\n\n    def _credential_accepted(self):\n        self._accept_login()\n\n    def _accept_login(self):\n        self._initial_login_complete = True\n        self._awaiting_login_acceptance = False\n        recovered = (\n            self._use_recovery_credentials\n            and self._recovery_credentials is not None\n        )\n        if recovered:\n            self._use_recovery_credentials = False\n            self._recovery_attempted = False\n            if not self._credential_recovery_pending:\n                self._commander.record_feature_error(\n                    \"admin-credentials\",\n                    \"desired credentials were rejected; resumed with the previous credentials \"\n                    \"while keeping the desired credentials for later logins\",\n                )\n            self._credential_recovery_pending = True\n        elif self._recovery_credentials is not None:\n            self._recovery_attempted = False\n            if self._credential_recovery_pending:\n                self._commander.resolve_feature_error(\n                    \"admin-credentials\",\n                    \"the desired credentials authenticated successfully\",\n                )\n                self._credential_recovery_pending = False\n        self._activate_pending_bootstrap_credentials()\n\n    def _command_prompt(self):\n        \"\"\"Accept password confirmation on versions that skip ``Welcome!``.\"\"\"\n        if self._awaiting_login_acceptance:\n            self._accept_login()\n        else:\n            self._initial_login_complete = True\n            self._activate_pending_bootstrap_credentials()\n\n    def _activate_pending_bootstrap_credentials(self):\n        if self._pending_bootstrap_activation:\n            self._activate_bootstrap_credentials()\n            self._pending_bootstrap_activation = False\n\n    @staticmethod\n    def _license_failed():\n        # SetLicense inspects the buffered command output when FortiOS returns\n        # to a prompt. Raising here would interrupt the driver at LIC_FAIL,\n        # before best-effort bootstrap can safely skip the feature.\n        return None\n\n    def _timeout(self):\n        self._idle_spins += 1\n        self._recover_unknown_stall()\n\n    def _unknown(self):\n        if self._last_known_state == FOSCliState.REBOOTING:\n            self._idle_spins += 1\n\n    @staticmethod\n    def _kernel_panic():\n        raise KernelPanicError(\"Kernel panic detected on serial console\")\n\n    def _note_unknown_output(self):\n        self._unknown_started_at = time.monotonic()\n\n    def _recover_unknown_stall(self):\n        if self._unknown_started_at is None:\n            return\n        if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:\n            return\n        if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:\n            raise RuntimeError(\"CLI remained in unknown state\")\n        self._unknown_newlines += 1\n        self._unknown_started_at = time.monotonic()\n        self._logger.warning(\n            \"CLI stuck in unknown state; sending newline \"\n            f\"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})\"\n        )\n        self._terminal.write(b\"\\r\")\n\n    def _clear_unknown_stall(self):\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n\n    def set_prompt_patterns(self, name_pattern):\n        if isinstance(name_pattern, str):\n            name_pattern = re.escape(name_pattern.encode())\n        self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb\"(?m)^[ \\t]*\" + name_pattern + rb\"[ \\t]+login:[ \\t]*\"\n        self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n        self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n\n    def _credential_rejected(self):\n        # A rejected interaction cannot establish the newly selected\n        # bootstrap password.  Do not activate it on a later unrelated\n        # acceptance or prompt.\n        self._pending_bootstrap_activation = False\n        if not self._initial_login_complete and self._blank_fallback_available:\n            self._send_blank_password = True\n            return\n        if (\n            self._allow_credential_recovery\n            and self._recovery_credentials is not None\n            and not self._recovery_attempted\n        ):\n            self._recovery_attempted = True\n            self._use_recovery_credentials = True\n            self._logger.warning(\n                \"Credentials were rejected; retrying with the previously accepted credentials\"\n            )\n            return\n        raise RuntimeError(\"Credential rejected\")\n\n    def _respond(self, state, response):\n        \"\"\"Write an interactive response to the CLI.\"\"\"\n        if isinstance(response, str):\n            response = response.encode()\n        self._logger.log(\n            TRACE_LEVEL,\n            \"Responding to CLI state %s with '%s'\",\n            state.name,\n            response,\n        )\n        self._terminal.write(bytes(response) + b\"\\r\")",
        "lineStart": 1,
        "lineEnd": 331,
        "totalLines": 331,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716400709,
      "end": 1793716400714
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d43263001VvdzdJn15ePaJH",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d3df9a001Z6KRG0YbSMbHXs",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 31532,
    "input": 13633,
    "output": 85,
    "reasoning": 2198,
    "cache": {
      "read": 15616,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d3df9a001Z6KRG0YbSMbHXs",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716379546,
    "completed": 1793716400742
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 31532,
    "input": 13633,
    "output": 85,
    "reasoning": 2198,
    "cache": {
      "read": 15616,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 16
step-start
{
  "type": "step-start",
  "id": "prt_1a1d4390f001FRBDzmTtGYc954",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4326c001skDYJshLglEpG0"
}
Reasoning
Now the driver flow: `process_state` → `_next_state` → if output and not matched: `commander.on_output(output)`, then `output = type(output)(b"")` (a fresh empty Data). So non-matched output (UNKNOWN or TN_TIMEOUT) is forwarded to commander.on_output ONCE, then replaced with empty Data for the state handling. Good — no duplicate forwarding of the same Data instance. But the commander's `attempt.on_output` discards the data from the buffer, so retained content is consumed. If inflight is None and no active feature consumes, output stays in buffer (discarded only when `_recovering`). Then next timeout exposes the same bytes again to `on_output` — a new Data each time (fresh expect), so a feature with an inflight command at that time would re-append previously-seen bytes into attempt.output. Hmm: consider sequence: timeout #1 with buffer B (no inflight) → on_output → nothing consumes → buffer retains B. Then a command is dispatched; timeout #2 exposes B again + possibly new → inflight.on_output appends B twice? No: attempt.output only gets B once because after first timeout, B stayed in buffer; second timeout Data covers B (+new); appends B (+new) once. But could attempt.output get B twice if between timeouts the inflight consumed B (discarded) and B re-appeared? Discard removes it from buffer, so no.

But duplicate content within one attempt: attempt.output could get B via timeout Data, and then the matching prompt arrives, `expect` returns matched output Data containing B+prompt; driver calls on_state(CMD_PROMPT, output) → commander.on_state → on_output(output) → inflight.on_output appends B again (since matched output includes everything up to the match). Wait: does expect consume the buffer on match? On match, the Data view covers matched bytes, and if not discarded, they remain in buffer. CommandAttempt.on_output always discards when it captures. So for a capturing command: timeout Data appended and discarded; then matched prompt Data (containing previously-seen bytes that... wait, if the timeout Data was discarded, the matched Data view's coverage starts after? Let me check terminal.py to understand Data coverage and discard semantics.

I read terminal.py earlier per handoff but I don't have its content here. Let me re-read terminal.py and the remaining files: test_common_stack_boundaries.py, test_common_stack_parsing.py (rest), features/base.py, features/license.py, and diff sections for README/pki/common.py/features/credentials.py/startup_config.py.
The driver forwards unmatched output to `commander.on_output` exactly once and then replaces it with an empty `Data`, which addresses the duplicate-forwarding concern. Now I need the `Terminal`/`Data` internals to confirm the view/coverage semantics, plus the remaining tests and feature files.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/terminal.py"
}

Output

<path>/source/head/fortinet/common/terminal.py</path>
<type>file</type>
<content>
1: import cmd
2: import logging
3: import re
4: import threading
5: import time
6: from collections import deque
7: from contextlib import contextmanager
8: 
9: from .common import TRACE_LEVEL
10: from .env import get_env
11: 
12: 
13: DEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024
14: BUFFER_LIMIT_ENV = "FOS_TERMINAL_BUFFER_LIMIT_BYTES"
15: READ_POLL_SECONDS = 0.001
16: RAW_SERIAL_LOG_ENV = "FOS_LOG_RAW_SERIAL"
17: 
18: 
19: def terminal_buffer_limit_bytes():
20:     configured = get_env(BUFFER_LIMIT_ENV)
21:     if not configured:
22:         return DEFAULT_BUFFER_LIMIT_BYTES
23: 
24:     limit = int(configured)
25:     if limit < 1:
26:         raise ValueError(f"{BUFFER_LIMIT_ENV} must be greater than zero")
27:     return limit
28: 
29: 
30: class Data:
31:     """A byte view returned by Terminal.expect with authority to discard itself."""
32: 
33:     def __init__(self, value, discard_callback=None, *, received_new_data=None):
34:         self.value = bytes(value)
35:         self._discard_callback = discard_callback
36:         self.discarded = False
37:         self.received_new_data = (
38:             bool(self.value) if received_new_data is None else received_new_data
39:         )
40: 
41:     def __bytes__(self):
42:         return self.value
43: 
44:     def __bool__(self):
45:         return bool(self.value)
46: 
47:     def __contains__(self, item):
48:         return item in self.value
49: 
50:     def __len__(self):
51:         return len(self.value)
52: 
53:     def __eq__(self, other):
54:         return self.value == (bytes(other) if isinstance(other, Data) else other)
55: 
56:     def __repr__(self):
57:         return repr(self.value)
58: 
59:     def startswith(self, *args, **kwargs):
60:         return self.value.startswith(*args, **kwargs)
61: 
62:     def decode(self, *args, **kwargs):
63:         return self.value.decode(*args, **kwargs)
64: 
65:     def discard(self, value=None):
66:         discard_value = self.value if value is None else bytes(value)
67:         if not discard_value:
68:             return
69:         if self._discard_callback:
70:             self._discard_callback(discard_value)
71:         self.discarded = True
72: 
73: 
74: class _ByteQueue:
75:     def __init__(self, max_size):
76:         self._max_size = max_size
77:         self._chunks = deque()
78:         self._size = 0
79:         self._closed = False
80:         self._error = None
81:         self._condition = threading.Condition()
82: 
83:     def put(self, data):
84:         offset = 0
85:         while offset < len(data):
86:             with self._condition:
87:                 while not self._closed and self._error is None and self._size >= self._max_size:
88:                     self._condition.wait()
89:                 if self._closed or self._error is not None:
90:                     return
91: 
92:                 available = self._max_size - self._size
93:                 chunk = bytes(data[offset:offset + available])
94:                 self._chunks.append(chunk)
95:                 self._size += len(chunk)
96:                 offset += len(chunk)
97:                 self._condition.notify_all()
98: 
99:     def get(self, timeout=None):
100:         deadline = None if timeout is None else time.monotonic() + timeout
101:         with self._condition:
102:             while not self._chunks and not self._closed and self._error is None:
103:                 if deadline is None:
104:                     self._condition.wait()
105:                     continue
106: 
107:                 remaining = deadline - time.monotonic()
108:                 if remaining <= 0:
109:                     return b""
110:                 self._condition.wait(remaining)
111: 
112:             if self._error is not None:
113:                 raise self._error
114:             if not self._chunks:
115:                 return b""
116: 
117:             data = b"".join(self._chunks)
118:             self._chunks.clear()
119:             self._size = 0
120:             self._condition.notify_all()
121:             return data
122: 
123:     def get_one(self, timeout=None):
124:         deadline = None if timeout is None else time.monotonic() + timeout
125:         with self._condition:
126:             while not self._chunks and not self._closed and self._error is None:
127:                 if deadline is None:
128:                     self._condition.wait()
129:                     continue
130: 
131:                 remaining = deadline - time.monotonic()
132:                 if remaining <= 0:
133:                     return b""
134:                 self._condition.wait(remaining)
135: 
136:             if self._error is not None:
137:                 raise self._error
138:             if not self._chunks:
139:                 return b""
140: 
141:             data = self._chunks.popleft()
142:             self._size -= len(data)
143:             self._condition.notify_all()
144:             return data
145: 
146:     def close(self):
147:         with self._condition:
148:             self._closed = True
149:             self._condition.notify_all()
150: 
151:     def fail(self, error):
152:         with self._condition:
153:             self._error = error
154:             self._condition.notify_all()
155: 
156: 
157: class Terminal:
158:     """Buffered access to the FortiOS serial console."""
159: 
160:     def __init__(self, connection, logger, default_wait="#"):
161:         self._connection = connection
162:         self._logger = logger
163:         self._default_wait = default_wait
164:         self._buffer = bytearray()
165:         self._buffer_limit = terminal_buffer_limit_bytes()
166:         self._read_queue = _ByteQueue(self._buffer_limit)
167:         self._write_queue = _ByteQueue(self._buffer_limit)
168:         self._reader_lock = threading.Lock()
169:         self._stop_reader = None
170:         self._reader = None
171:         self._writer_lock = threading.Lock()
172:         self._writer = None
173:         self._output_suppression_depth = 0
174:         self._output_suppression_context = None
175: 
176:     def write(self, data):
177:         if isinstance(data, str):
178:             data = data.encode()
179:         self._ensure_writer()
180:         self._write_queue.put(data)
181: 
182:     def wait_write(
183:         self,
184:         cmd,
185:         wait="__defaultpattern__",
186:         clean_buffer=False,
187:         hold="",
188:         timeout=None,
189:     ):
190:         if wait:
191:             if wait == "__defaultpattern__":
192:                 wait = self._default_wait
193:             self._logger.info(f"waiting for '{wait}' on serial console")
194:             pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)
195:             _, match, output = self.expect([pattern], timeout)
196: 
197:             while match and hold and hold.encode() in output:
198:                 self._logger.info(
199:                     f"Holding pattern '{hold}' detected, retrying in 10s..."
200:                 )
201:                 self.write(b"\r")
202:                 time.sleep(10)
203:                 _, match, output = self.expect([pattern], timeout)
204: 
205:             if not match:
206:                 self._logger.info(
207:                     f"timed out waiting for '{wait}' on serial console"
208:                 )
209: 
210:         if clean_buffer:
211:             self._buffer.clear()
212: 
213:         self._logger.debug(f"writing to serial console: '{cmd}'")
214:         self.write(f"{cmd}\r")
215: 
216:     def expect(self, regex_list, timeout=None):
217:         """Read until a pattern matches, retaining unmatched data across calls.
218: 
219:         The match ending earliest in the buffered stream wins. Data through that
220:         match is returned and discarded; data after it remains buffered.
221:         On timeout, the entire unmatched buffer is returned for inspection and
222:         stays buffered unless the caller explicitly discards it.
223:         """
224:         self._ensure_reader()
225:         deadline = None if timeout is None else time.monotonic() + timeout
226:         received_new_data = False
227:         result = self._match(regex_list)
228: 
229:         while result is None:
230:             remaining = None if deadline is None else deadline - time.monotonic()
231:             if remaining is not None and remaining <= 0:
232:                 return -1, None, Data(
233:                     self._buffer,
234:                     self._discard_prefix,
235:                     received_new_data=received_new_data,
236:                 )
237: 
238:             data = self._read_queue.get(remaining)
239:             if data:
240:                 self._buffer.extend(data)
241:                 self._enforce_buffer_limit()
242:                 received_new_data = True
243:                 if (
244:                     get_env(RAW_SERIAL_LOG_ENV, "").lower() in ("1", "true", "yes")
245:                     and self._output_suppression_depth == 0
246:                 ):
247:                     self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")
248:                 result = self._match(regex_list)
249:                 continue
250: 
251:             if deadline is not None and time.monotonic() >= deadline:
252:                 return -1, None, Data(
253:                     self._buffer,
254:                     self._discard_prefix,
255:                     received_new_data=received_new_data,
256:                 )
257: 
258:         index, match = result
259:         consumed = bytes(self._buffer[:match.end()])
260:         stable_match = re.search(regex_list[index], consumed)
261:         del self._buffer[:match.end()]
262:         return index, stable_match, Data(consumed)
263: 
264:     def _discard_prefix(self, data):
265:         """Discard bytes that a caller has consumed from the retained buffer."""
266:         if not data:
267:             return
268:         if not self._buffer.startswith(data):
269:             message = "Refusing to discard non-prefix terminal output"
270:             if self._logger.isEnabledFor(TRACE_LEVEL):
271:                 message += f": data={data!r}; buffer={self._buffer!r}"
272:             self._logger.warning(message)
273:             return
274:         del self._buffer[:len(data)]
275: 
276:     def _enforce_buffer_limit(self):
277:         if len(self._buffer) <= self._buffer_limit:
278:             return
279: 
280:         self._logger.error(
281:             "Terminal buffer exceeded %s bytes. Tail: %r",
282:             self._buffer_limit,
283:             bytes(self._buffer[-512:]),
284:         )
285:         raise RuntimeError(
286:             f"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed"
287:         )
288: 
289:     def _ensure_reader(self):
290:         with self._reader_lock:
291:             if self._reader is not None and self._reader.is_alive():
292:                 return
293: 
294:             self._read_queue = _ByteQueue(self._buffer_limit)
295:             self._stop_reader = threading.Event()
296:             self._reader = threading.Thread(
297:                 target=self._read_forever,
298:                 args=(self._stop_reader, self._read_queue),
299:                 name="fortios-terminal-reader",
300:             )
301:             self._reader.daemon = True
302:             self._reader.start()
303: 
304:     def _read_forever(self, stop_reader, read_queue):
305:         while not stop_reader.is_set():
306:             try:
307:                 data = self._connection.read_very_eager()
308:             except Exception as error:
309:                 if not stop_reader.is_set():
310:                     self._logger.exception("Terminal reader failed")
311:                     read_queue.fail(error)
312:                 return
313: 
314:             if data:
315:                 read_queue.put(data)
316:             else:
317:                 stop_reader.wait(READ_POLL_SECONDS)
318: 
319:     def _ensure_writer(self):
320:         with self._writer_lock:
321:             if self._writer is not None and self._writer.is_alive():
322:                 return
323: 
324:             self._write_queue = _ByteQueue(self._buffer_limit)
325:             self._writer = threading.Thread(
326:                 target=self._write_forever,
327:                 args=(self._write_queue,),
328:                 name="fortios-terminal-writer",
329:             )
330:             self._writer.daemon = True
331:             self._writer.start()
332: 
333:     def _write_forever(self, write_queue):
334:         while True:
335:             try:
336:                 data = write_queue.get_one()
337:             except Exception:
338:                 self._logger.exception("Terminal writer failed")
339:                 return
340: 
341:             if not data:
342:                 return
343: 
344:             try:
345:                 self._connection.write(data)
346:             except Exception:
347:                 self._logger.exception("Terminal writer failed")
348:                 return
349: 
350:     def close(self):
351:         with self._reader_lock:
352:             reader = self._reader
353:             stop_reader = self._stop_reader
354:             read_queue = self._read_queue
355:             self._reader = None
356:             self._stop_reader = None
357: 
358:         with self._writer_lock:
359:             writer = self._writer
360:             write_queue = self._write_queue
361:             self._writer = None
362: 
363:         if stop_reader is not None:
364:             stop_reader.set()
365:         read_queue.close()
366:         write_queue.close()
367:         if writer is not None:
368:             writer.join(1)
369:         self._buffer.clear()
370:         self._connection.close()
371:         if reader is not None:
372:             reader.join(1)
373: 
374:     @contextmanager
375:     def suppress_output(self):
376:         if self._output_suppression_depth == 0:
377:             self._output_suppression_context = self._connection.suppress_output()
378:             self._output_suppression_context.__enter__()
379:         self._output_suppression_depth += 1
380:         try:
381:             yield
382:         finally:
383:             self._output_suppression_depth -= 1
384:             if self._output_suppression_depth == 0:
385:                 try:
386:                     self._output_suppression_context.__exit__(None, None, None)
387:                 finally:
388:                     self._output_suppression_context = None
389: 
390:     def _match(self, regex_list):
391:         winner = None
392:         for index, pattern in enumerate(regex_list):
393:             match = re.search(pattern, self._buffer)
394:             if match is None:
395:                 continue
396:             if winner is None or match.end() < winner[1].end():
397:                 winner = index, match
398:         return winner

(End of file - total 398 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d455f7001OwZ1NVWmWAh338",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4326c001skDYJshLglEpG0",
  "callID": "call_75b973bc12f14cd898666105",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/terminal.py"
    },
    "output": "<path>/source/head/fortinet/common/terminal.py</path>\n<type>file</type>\n<content>\n1: import cmd\n2: import logging\n3: import re\n4: import threading\n5: import time\n6: from collections import deque\n7: from contextlib import contextmanager\n8: \n9: from .common import TRACE_LEVEL\n10: from .env import get_env\n11: \n12: \n13: DEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024\n14: BUFFER_LIMIT_ENV = \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\"\n15: READ_POLL_SECONDS = 0.001\n16: RAW_SERIAL_LOG_ENV = \"FOS_LOG_RAW_SERIAL\"\n17: \n18: \n19: def terminal_buffer_limit_bytes():\n20:     configured = get_env(BUFFER_LIMIT_ENV)\n21:     if not configured:\n22:         return DEFAULT_BUFFER_LIMIT_BYTES\n23: \n24:     limit = int(configured)\n25:     if limit < 1:\n26:         raise ValueError(f\"{BUFFER_LIMIT_ENV} must be greater than zero\")\n27:     return limit\n28: \n29: \n30: class Data:\n31:     \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n32: \n33:     def __init__(self, value, discard_callback=None, *, received_new_data=None):\n34:         self.value = bytes(value)\n35:         self._discard_callback = discard_callback\n36:         self.discarded = False\n37:         self.received_new_data = (\n38:             bool(self.value) if received_new_data is None else received_new_data\n39:         )\n40: \n41:     def __bytes__(self):\n42:         return self.value\n43: \n44:     def __bool__(self):\n45:         return bool(self.value)\n46: \n47:     def __contains__(self, item):\n48:         return item in self.value\n49: \n50:     def __len__(self):\n51:         return len(self.value)\n52: \n53:     def __eq__(self, other):\n54:         return self.value == (bytes(other) if isinstance(other, Data) else other)\n55: \n56:     def __repr__(self):\n57:         return repr(self.value)\n58: \n59:     def startswith(self, *args, **kwargs):\n60:         return self.value.startswith(*args, **kwargs)\n61: \n62:     def decode(self, *args, **kwargs):\n63:         return self.value.decode(*args, **kwargs)\n64: \n65:     def discard(self, value=None):\n66:         discard_value = self.value if value is None else bytes(value)\n67:         if not discard_value:\n68:             return\n69:         if self._discard_callback:\n70:             self._discard_callback(discard_value)\n71:         self.discarded = True\n72: \n73: \n74: class _ByteQueue:\n75:     def __init__(self, max_size):\n76:         self._max_size = max_size\n77:         self._chunks = deque()\n78:         self._size = 0\n79:         self._closed = False\n80:         self._error = None\n81:         self._condition = threading.Condition()\n82: \n83:     def put(self, data):\n84:         offset = 0\n85:         while offset < len(data):\n86:             with self._condition:\n87:                 while not self._closed and self._error is None and self._size >= self._max_size:\n88:                     self._condition.wait()\n89:                 if self._closed or self._error is not None:\n90:                     return\n91: \n92:                 available = self._max_size - self._size\n93:                 chunk = bytes(data[offset:offset + available])\n94:                 self._chunks.append(chunk)\n95:                 self._size += len(chunk)\n96:                 offset += len(chunk)\n97:                 self._condition.notify_all()\n98: \n99:     def get(self, timeout=None):\n100:         deadline = None if timeout is None else time.monotonic() + timeout\n101:         with self._condition:\n102:             while not self._chunks and not self._closed and self._error is None:\n103:                 if deadline is None:\n104:                     self._condition.wait()\n105:                     continue\n106: \n107:                 remaining = deadline - time.monotonic()\n108:                 if remaining <= 0:\n109:                     return b\"\"\n110:                 self._condition.wait(remaining)\n111: \n112:             if self._error is not None:\n113:                 raise self._error\n114:             if not self._chunks:\n115:                 return b\"\"\n116: \n117:             data = b\"\".join(self._chunks)\n118:             self._chunks.clear()\n119:             self._size = 0\n120:             self._condition.notify_all()\n121:             return data\n122: \n123:     def get_one(self, timeout=None):\n124:         deadline = None if timeout is None else time.monotonic() + timeout\n125:         with self._condition:\n126:             while not self._chunks and not self._closed and self._error is None:\n127:                 if deadline is None:\n128:                     self._condition.wait()\n129:                     continue\n130: \n131:                 remaining = deadline - time.monotonic()\n132:                 if remaining <= 0:\n133:                     return b\"\"\n134:                 self._condition.wait(remaining)\n135: \n136:             if self._error is not None:\n137:                 raise self._error\n138:             if not self._chunks:\n139:                 return b\"\"\n140: \n141:             data = self._chunks.popleft()\n142:             self._size -= len(data)\n143:             self._condition.notify_all()\n144:             return data\n145: \n146:     def close(self):\n147:         with self._condition:\n148:             self._closed = True\n149:             self._condition.notify_all()\n150: \n151:     def fail(self, error):\n152:         with self._condition:\n153:             self._error = error\n154:             self._condition.notify_all()\n155: \n156: \n157: class Terminal:\n158:     \"\"\"Buffered access to the FortiOS serial console.\"\"\"\n159: \n160:     def __init__(self, connection, logger, default_wait=\"#\"):\n161:         self._connection = connection\n162:         self._logger = logger\n163:         self._default_wait = default_wait\n164:         self._buffer = bytearray()\n165:         self._buffer_limit = terminal_buffer_limit_bytes()\n166:         self._read_queue = _ByteQueue(self._buffer_limit)\n167:         self._write_queue = _ByteQueue(self._buffer_limit)\n168:         self._reader_lock = threading.Lock()\n169:         self._stop_reader = None\n170:         self._reader = None\n171:         self._writer_lock = threading.Lock()\n172:         self._writer = None\n173:         self._output_suppression_depth = 0\n174:         self._output_suppression_context = None\n175: \n176:     def write(self, data):\n177:         if isinstance(data, str):\n178:             data = data.encode()\n179:         self._ensure_writer()\n180:         self._write_queue.put(data)\n181: \n182:     def wait_write(\n183:         self,\n184:         cmd,\n185:         wait=\"__defaultpattern__\",\n186:         clean_buffer=False,\n187:         hold=\"\",\n188:         timeout=None,\n189:     ):\n190:         if wait:\n191:             if wait == \"__defaultpattern__\":\n192:                 wait = self._default_wait\n193:             self._logger.info(f\"waiting for '{wait}' on serial console\")\n194:             pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)\n195:             _, match, output = self.expect([pattern], timeout)\n196: \n197:             while match and hold and hold.encode() in output:\n198:                 self._logger.info(\n199:                     f\"Holding pattern '{hold}' detected, retrying in 10s...\"\n200:                 )\n201:                 self.write(b\"\\r\")\n202:                 time.sleep(10)\n203:                 _, match, output = self.expect([pattern], timeout)\n204: \n205:             if not match:\n206:                 self._logger.info(\n207:                     f\"timed out waiting for '{wait}' on serial console\"\n208:                 )\n209: \n210:         if clean_buffer:\n211:             self._buffer.clear()\n212: \n213:         self._logger.debug(f\"writing to serial console: '{cmd}'\")\n214:         self.write(f\"{cmd}\\r\")\n215: \n216:     def expect(self, regex_list, timeout=None):\n217:         \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n218: \n219:         The match ending earliest in the buffered stream wins. Data through that\n220:         match is returned and discarded; data after it remains buffered.\n221:         On timeout, the entire unmatched buffer is returned for inspection and\n222:         stays buffered unless the caller explicitly discards it.\n223:         \"\"\"\n224:         self._ensure_reader()\n225:         deadline = None if timeout is None else time.monotonic() + timeout\n226:         received_new_data = False\n227:         result = self._match(regex_list)\n228: \n229:         while result is None:\n230:             remaining = None if deadline is None else deadline - time.monotonic()\n231:             if remaining is not None and remaining <= 0:\n232:                 return -1, None, Data(\n233:                     self._buffer,\n234:                     self._discard_prefix,\n235:                     received_new_data=received_new_data,\n236:                 )\n237: \n238:             data = self._read_queue.get(remaining)\n239:             if data:\n240:                 self._buffer.extend(data)\n241:                 self._enforce_buffer_limit()\n242:                 received_new_data = True\n243:                 if (\n244:                     get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n245:                     and self._output_suppression_depth == 0\n246:                 ):\n247:                     self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n248:                 result = self._match(regex_list)\n249:                 continue\n250: \n251:             if deadline is not None and time.monotonic() >= deadline:\n252:                 return -1, None, Data(\n253:                     self._buffer,\n254:                     self._discard_prefix,\n255:                     received_new_data=received_new_data,\n256:                 )\n257: \n258:         index, match = result\n259:         consumed = bytes(self._buffer[:match.end()])\n260:         stable_match = re.search(regex_list[index], consumed)\n261:         del self._buffer[:match.end()]\n262:         return index, stable_match, Data(consumed)\n263: \n264:     def _discard_prefix(self, data):\n265:         \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n266:         if not data:\n267:             return\n268:         if not self._buffer.startswith(data):\n269:             message = \"Refusing to discard non-prefix terminal output\"\n270:             if self._logger.isEnabledFor(TRACE_LEVEL):\n271:                 message += f\": data={data!r}; buffer={self._buffer!r}\"\n272:             self._logger.warning(message)\n273:             return\n274:         del self._buffer[:len(data)]\n275: \n276:     def _enforce_buffer_limit(self):\n277:         if len(self._buffer) <= self._buffer_limit:\n278:             return\n279: \n280:         self._logger.error(\n281:             \"Terminal buffer exceeded %s bytes. Tail: %r\",\n282:             self._buffer_limit,\n283:             bytes(self._buffer[-512:]),\n284:         )\n285:         raise RuntimeError(\n286:             f\"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed\"\n287:         )\n288: \n289:     def _ensure_reader(self):\n290:         with self._reader_lock:\n291:             if self._reader is not None and self._reader.is_alive():\n292:                 return\n293: \n294:             self._read_queue = _ByteQueue(self._buffer_limit)\n295:             self._stop_reader = threading.Event()\n296:             self._reader = threading.Thread(\n297:                 target=self._read_forever,\n298:                 args=(self._stop_reader, self._read_queue),\n299:                 name=\"fortios-terminal-reader\",\n300:             )\n301:             self._reader.daemon = True\n302:             self._reader.start()\n303: \n304:     def _read_forever(self, stop_reader, read_queue):\n305:         while not stop_reader.is_set():\n306:             try:\n307:                 data = self._connection.read_very_eager()\n308:             except Exception as error:\n309:                 if not stop_reader.is_set():\n310:                     self._logger.exception(\"Terminal reader failed\")\n311:                     read_queue.fail(error)\n312:                 return\n313: \n314:             if data:\n315:                 read_queue.put(data)\n316:             else:\n317:                 stop_reader.wait(READ_POLL_SECONDS)\n318: \n319:     def _ensure_writer(self):\n320:         with self._writer_lock:\n321:             if self._writer is not None and self._writer.is_alive():\n322:                 return\n323: \n324:             self._write_queue = _ByteQueue(self._buffer_limit)\n325:             self._writer = threading.Thread(\n326:                 target=self._write_forever,\n327:                 args=(self._write_queue,),\n328:                 name=\"fortios-terminal-writer\",\n329:             )\n330:             self._writer.daemon = True\n331:             self._writer.start()\n332: \n333:     def _write_forever(self, write_queue):\n334:         while True:\n335:             try:\n336:                 data = write_queue.get_one()\n337:             except Exception:\n338:                 self._logger.exception(\"Terminal writer failed\")\n339:                 return\n340: \n341:             if not data:\n342:                 return\n343: \n344:             try:\n345:                 self._connection.write(data)\n346:             except Exception:\n347:                 self._logger.exception(\"Terminal writer failed\")\n348:                 return\n349: \n350:     def close(self):\n351:         with self._reader_lock:\n352:             reader = self._reader\n353:             stop_reader = self._stop_reader\n354:             read_queue = self._read_queue\n355:             self._reader = None\n356:             self._stop_reader = None\n357: \n358:         with self._writer_lock:\n359:             writer = self._writer\n360:             write_queue = self._write_queue\n361:             self._writer = None\n362: \n363:         if stop_reader is not None:\n364:             stop_reader.set()\n365:         read_queue.close()\n366:         write_queue.close()\n367:         if writer is not None:\n368:             writer.join(1)\n369:         self._buffer.clear()\n370:         self._connection.close()\n371:         if reader is not None:\n372:             reader.join(1)\n373: \n374:     @contextmanager\n375:     def suppress_output(self):\n376:         if self._output_suppression_depth == 0:\n377:             self._output_suppression_context = self._connection.suppress_output()\n378:             self._output_suppression_context.__enter__()\n379:         self._output_suppression_depth += 1\n380:         try:\n381:             yield\n382:         finally:\n383:             self._output_suppression_depth -= 1\n384:             if self._output_suppression_depth == 0:\n385:                 try:\n386:                     self._output_suppression_context.__exit__(None, None, None)\n387:                 finally:\n388:                     self._output_suppression_context = None\n389: \n390:     def _match(self, regex_list):\n391:         winner = None\n392:         for index, pattern in enumerate(regex_list):\n393:             match = re.search(pattern, self._buffer)\n394:             if match is None:\n395:                 continue\n396:             if winner is None or match.end() < winner[1].end():\n397:                 winner = index, match\n398:         return winner\n\n(End of file - total 398 lines)\n</content>",
    "title": "source/head/fortinet/common/terminal.py",
    "metadata": {
      "preview": "import cmd\nimport logging\nimport re\nimport threading\nimport time\nfrom collections import deque\nfrom contextlib import contextmanager\n\nfrom .common import TRACE_LEVEL\nfrom .env import get_env\n\n\nDEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024\nBUFFER_LIMIT_ENV = \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\"\nREAD_POLL_SECONDS = 0.001\nRAW_SERIAL_LOG_ENV = \"FOS_LOG_RAW_SERIAL\"\n\n\ndef terminal_buffer_limit_bytes():\n    configured = get_env(BUFFER_LIMIT_ENV)",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/terminal.py",
        "text": "import cmd\nimport logging\nimport re\nimport threading\nimport time\nfrom collections import deque\nfrom contextlib import contextmanager\n\nfrom .common import TRACE_LEVEL\nfrom .env import get_env\n\n\nDEFAULT_BUFFER_LIMIT_BYTES = 1024 * 1024\nBUFFER_LIMIT_ENV = \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\"\nREAD_POLL_SECONDS = 0.001\nRAW_SERIAL_LOG_ENV = \"FOS_LOG_RAW_SERIAL\"\n\n\ndef terminal_buffer_limit_bytes():\n    configured = get_env(BUFFER_LIMIT_ENV)\n    if not configured:\n        return DEFAULT_BUFFER_LIMIT_BYTES\n\n    limit = int(configured)\n    if limit < 1:\n        raise ValueError(f\"{BUFFER_LIMIT_ENV} must be greater than zero\")\n    return limit\n\n\nclass Data:\n    \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n\n    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n        self.value = bytes(value)\n        self._discard_callback = discard_callback\n        self.discarded = False\n        self.received_new_data = (\n            bool(self.value) if received_new_data is None else received_new_data\n        )\n\n    def __bytes__(self):\n        return self.value\n\n    def __bool__(self):\n        return bool(self.value)\n\n    def __contains__(self, item):\n        return item in self.value\n\n    def __len__(self):\n        return len(self.value)\n\n    def __eq__(self, other):\n        return self.value == (bytes(other) if isinstance(other, Data) else other)\n\n    def __repr__(self):\n        return repr(self.value)\n\n    def startswith(self, *args, **kwargs):\n        return self.value.startswith(*args, **kwargs)\n\n    def decode(self, *args, **kwargs):\n        return self.value.decode(*args, **kwargs)\n\n    def discard(self, value=None):\n        discard_value = self.value if value is None else bytes(value)\n        if not discard_value:\n            return\n        if self._discard_callback:\n            self._discard_callback(discard_value)\n        self.discarded = True\n\n\nclass _ByteQueue:\n    def __init__(self, max_size):\n        self._max_size = max_size\n        self._chunks = deque()\n        self._size = 0\n        self._closed = False\n        self._error = None\n        self._condition = threading.Condition()\n\n    def put(self, data):\n        offset = 0\n        while offset < len(data):\n            with self._condition:\n                while not self._closed and self._error is None and self._size >= self._max_size:\n                    self._condition.wait()\n                if self._closed or self._error is not None:\n                    return\n\n                available = self._max_size - self._size\n                chunk = bytes(data[offset:offset + available])\n                self._chunks.append(chunk)\n                self._size += len(chunk)\n                offset += len(chunk)\n                self._condition.notify_all()\n\n    def get(self, timeout=None):\n        deadline = None if timeout is None else time.monotonic() + timeout\n        with self._condition:\n            while not self._chunks and not self._closed and self._error is None:\n                if deadline is None:\n                    self._condition.wait()\n                    continue\n\n                remaining = deadline - time.monotonic()\n                if remaining <= 0:\n                    return b\"\"\n                self._condition.wait(remaining)\n\n            if self._error is not None:\n                raise self._error\n            if not self._chunks:\n                return b\"\"\n\n            data = b\"\".join(self._chunks)\n            self._chunks.clear()\n            self._size = 0\n            self._condition.notify_all()\n            return data\n\n    def get_one(self, timeout=None):\n        deadline = None if timeout is None else time.monotonic() + timeout\n        with self._condition:\n            while not self._chunks and not self._closed and self._error is None:\n                if deadline is None:\n                    self._condition.wait()\n                    continue\n\n                remaining = deadline - time.monotonic()\n                if remaining <= 0:\n                    return b\"\"\n                self._condition.wait(remaining)\n\n            if self._error is not None:\n                raise self._error\n            if not self._chunks:\n                return b\"\"\n\n            data = self._chunks.popleft()\n            self._size -= len(data)\n            self._condition.notify_all()\n            return data\n\n    def close(self):\n        with self._condition:\n            self._closed = True\n            self._condition.notify_all()\n\n    def fail(self, error):\n        with self._condition:\n            self._error = error\n            self._condition.notify_all()\n\n\nclass Terminal:\n    \"\"\"Buffered access to the FortiOS serial console.\"\"\"\n\n    def __init__(self, connection, logger, default_wait=\"#\"):\n        self._connection = connection\n        self._logger = logger\n        self._default_wait = default_wait\n        self._buffer = bytearray()\n        self._buffer_limit = terminal_buffer_limit_bytes()\n        self._read_queue = _ByteQueue(self._buffer_limit)\n        self._write_queue = _ByteQueue(self._buffer_limit)\n        self._reader_lock = threading.Lock()\n        self._stop_reader = None\n        self._reader = None\n        self._writer_lock = threading.Lock()\n        self._writer = None\n        self._output_suppression_depth = 0\n        self._output_suppression_context = None\n\n    def write(self, data):\n        if isinstance(data, str):\n            data = data.encode()\n        self._ensure_writer()\n        self._write_queue.put(data)\n\n    def wait_write(\n        self,\n        cmd,\n        wait=\"__defaultpattern__\",\n        clean_buffer=False,\n        hold=\"\",\n        timeout=None,\n    ):\n        if wait:\n            if wait == \"__defaultpattern__\":\n                wait = self._default_wait\n            self._logger.info(f\"waiting for '{wait}' on serial console\")\n            pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)\n            _, match, output = self.expect([pattern], timeout)\n\n            while match and hold and hold.encode() in output:\n                self._logger.info(\n                    f\"Holding pattern '{hold}' detected, retrying in 10s...\"\n                )\n                self.write(b\"\\r\")\n                time.sleep(10)\n                _, match, output = self.expect([pattern], timeout)\n\n            if not match:\n                self._logger.info(\n                    f\"timed out waiting for '{wait}' on serial console\"\n                )\n\n        if clean_buffer:\n            self._buffer.clear()\n\n        self._logger.debug(f\"writing to serial console: '{cmd}'\")\n        self.write(f\"{cmd}\\r\")\n\n    def expect(self, regex_list, timeout=None):\n        \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n\n        The match ending earliest in the buffered stream wins. Data through that\n        match is returned and discarded; data after it remains buffered.\n        On timeout, the entire unmatched buffer is returned for inspection and\n        stays buffered unless the caller explicitly discards it.\n        \"\"\"\n        self._ensure_reader()\n        deadline = None if timeout is None else time.monotonic() + timeout\n        received_new_data = False\n        result = self._match(regex_list)\n\n        while result is None:\n            remaining = None if deadline is None else deadline - time.monotonic()\n            if remaining is not None and remaining <= 0:\n                return -1, None, Data(\n                    self._buffer,\n                    self._discard_prefix,\n                    received_new_data=received_new_data,\n                )\n\n            data = self._read_queue.get(remaining)\n            if data:\n                self._buffer.extend(data)\n                self._enforce_buffer_limit()\n                received_new_data = True\n                if (\n                    get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n                    and self._output_suppression_depth == 0\n                ):\n                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n                result = self._match(regex_list)\n                continue\n\n            if deadline is not None and time.monotonic() >= deadline:\n                return -1, None, Data(\n                    self._buffer,\n                    self._discard_prefix,\n                    received_new_data=received_new_data,\n                )\n\n        index, match = result\n        consumed = bytes(self._buffer[:match.end()])\n        stable_match = re.search(regex_list[index], consumed)\n        del self._buffer[:match.end()]\n        return index, stable_match, Data(consumed)\n\n    def _discard_prefix(self, data):\n        \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n        if not data:\n            return\n        if not self._buffer.startswith(data):\n            message = \"Refusing to discard non-prefix terminal output\"\n            if self._logger.isEnabledFor(TRACE_LEVEL):\n                message += f\": data={data!r}; buffer={self._buffer!r}\"\n            self._logger.warning(message)\n            return\n        del self._buffer[:len(data)]\n\n    def _enforce_buffer_limit(self):\n        if len(self._buffer) <= self._buffer_limit:\n            return\n\n        self._logger.error(\n            \"Terminal buffer exceeded %s bytes. Tail: %r\",\n            self._buffer_limit,\n            bytes(self._buffer[-512:]),\n        )\n        raise RuntimeError(\n            f\"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed\"\n        )\n\n    def _ensure_reader(self):\n        with self._reader_lock:\n            if self._reader is not None and self._reader.is_alive():\n                return\n\n            self._read_queue = _ByteQueue(self._buffer_limit)\n            self._stop_reader = threading.Event()\n            self._reader = threading.Thread(\n                target=self._read_forever,\n                args=(self._stop_reader, self._read_queue),\n                name=\"fortios-terminal-reader\",\n            )\n            self._reader.daemon = True\n            self._reader.start()\n\n    def _read_forever(self, stop_reader, read_queue):\n        while not stop_reader.is_set():\n            try:\n                data = self._connection.read_very_eager()\n            except Exception as error:\n                if not stop_reader.is_set():\n                    self._logger.exception(\"Terminal reader failed\")\n                    read_queue.fail(error)\n                return\n\n            if data:\n                read_queue.put(data)\n            else:\n                stop_reader.wait(READ_POLL_SECONDS)\n\n    def _ensure_writer(self):\n        with self._writer_lock:\n            if self._writer is not None and self._writer.is_alive():\n                return\n\n            self._write_queue = _ByteQueue(self._buffer_limit)\n            self._writer = threading.Thread(\n                target=self._write_forever,\n                args=(self._write_queue,),\n                name=\"fortios-terminal-writer\",\n            )\n            self._writer.daemon = True\n            self._writer.start()\n\n    def _write_forever(self, write_queue):\n        while True:\n            try:\n                data = write_queue.get_one()\n            except Exception:\n                self._logger.exception(\"Terminal writer failed\")\n                return\n\n            if not data:\n                return\n\n            try:\n                self._connection.write(data)\n            except Exception:\n                self._logger.exception(\"Terminal writer failed\")\n                return\n\n    def close(self):\n        with self._reader_lock:\n            reader = self._reader\n            stop_reader = self._stop_reader\n            read_queue = self._read_queue\n            self._reader = None\n            self._stop_reader = None\n\n        with self._writer_lock:\n            writer = self._writer\n            write_queue = self._write_queue\n            self._writer = None\n\n        if stop_reader is not None:\n            stop_reader.set()\n        read_queue.close()\n        write_queue.close()\n        if writer is not None:\n            writer.join(1)\n        self._buffer.clear()\n        self._connection.close()\n        if reader is not None:\n            reader.join(1)\n\n    @contextmanager\n    def suppress_output(self):\n        if self._output_suppression_depth == 0:\n            self._output_suppression_context = self._connection.suppress_output()\n            self._output_suppression_context.__enter__()\n        self._output_suppression_depth += 1\n        try:\n            yield\n        finally:\n            self._output_suppression_depth -= 1\n            if self._output_suppression_depth == 0:\n                try:\n                    self._output_suppression_context.__exit__(None, None, None)\n                finally:\n                    self._output_suppression_context = None\n\n    def _match(self, regex_list):\n        winner = None\n        for index, pattern in enumerate(regex_list):\n            match = re.search(pattern, self._buffer)\n            if match is None:\n                continue\n            if winner is None or match.end() < winner[1].end():\n                winner = index, match\n        return winner",
        "lineStart": 1,
        "lineEnd": 398,
        "totalLines": 398,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716409851,
      "end": 1793716409856
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/base.py"
}

Output

<path>/source/head/fortinet/common/features/base.py</path>
<type>file</type>
<content>
1: """Shared feature lifecycle primitives."""
2: 
3: 
4: class Feature:
5:     def __init__(self, vm, commander, name):
6:         self.vm = vm
7:         self.commander = commander
8:         self.name = name
9:         self._completed = False
10:         self._current_attempt = None
11: 
12:     @property
13:     def completed(self):
14:         return self._completed
15: 
16:     def mark_completed(self):
17:         self._completed = True
18: 
19:     @property
20:     def completion_message(self):
21:         return None
22: 
23:     def begin_activation(self):
24:         """Prepare this feature instance for an initial or later command stage."""
25:         self._completed = False
26:         self._current_attempt = None
27: 
28:     @property
29:     def current_attempt(self):
30:         return self._current_attempt
31: 
32:     @property
33:     def current_command(self):
34:         return self._current_attempt.spec if self._current_attempt else None
35: 
36:     @property
37:     def command_output(self):
38:         return bytes(self._current_attempt.output) if self._current_attempt else b""
39: 
40:     def activate(self):
41:         self.commander.feature_complete(self)
42: 
43:     def on_command_dispatched(self, attempt):
44:         self._current_attempt = attempt
45: 
46:     def on_output(self, output):
47:         return False
48: 
49:     def on_command_executed(self, command, state):
50:         pass
51: 
52:     def on_block_complete(self):
53:         self.commander.feature_complete(self)
54: 
55:     def on_session_loss(self, attempt):
56:         return attempt.spec.session_loss
57: 
58:     def on_context_loss(self, attempt):
59:         """Choose whether the commander may replay this interrupted block."""
60:         return attempt.spec.context_loss
61: 
62:     def reversal_blocks(self):
63:         """Return command blocks that completely reverse this feature's work."""
64:         return []
65: 
66:     def undo(self):
67:         """Return a feature stage that reverses this completed feature."""
68:         return _FeatureUndo(self.vm, self.commander, self)
69: 
70:     @property
71:     def file_path(self):
72:         """Return the optional file path watched for this feature."""
73:         return None
74: 
75:     def on_file_detected(self, path):
76:         pass
77: 
78:     def on_file_deleted(self, path):
79:         pass
80: 
81:     def on_file_modified(self, path):
82:         pass
83: 
84: 
85: class StaticFeature(Feature):
86:     """A feature whose command blocks are known when it is constructed."""
87: 
88:     def __init__(self, vm, commander, name, blocks, on_complete=None):
89:         super().__init__(vm, commander, name)
90:         self._blocks = list(blocks)
91:         self._on_complete = on_complete
92: 
93:     def activate(self):
94:         self._submit_next()
95: 
96:     def _submit_next(self):
97:         if self._blocks:
98:             self.commander.submit_block(self, self._blocks.pop(0))
99:             return
100:         if self._on_complete:
101:             self._on_complete()
102:         self.commander.feature_complete(self)
103: 
104:     def on_block_complete(self):
105:         self._submit_next()
106: 
107: 
108: class _FeatureUndo(StaticFeature):
109:     """A scheduled reversal stage created by ``Feature.undo``."""
110: 
111:     def __init__(self, vm, commander, target):
112:         super().__init__(vm, commander, f"undo-{target.name}", ())
113:         self._target = target
114: 
115:     def activate(self):
116:         if not self._target.completed:
117:             raise RuntimeError(f"Cannot undo incomplete feature {self._target.name}")
118:         self._blocks = list(self._target.reversal_blocks())
119:         super().activate()

(End of file - total 119 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d45647001gKTMKXbt7e719a",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4326c001skDYJshLglEpG0",
  "callID": "call_b0cd04716bb64a8ba2efcf3c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/base.py"
    },
    "output": "<path>/source/head/fortinet/common/features/base.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Shared feature lifecycle primitives.\"\"\"\n2: \n3: \n4: class Feature:\n5:     def __init__(self, vm, commander, name):\n6:         self.vm = vm\n7:         self.commander = commander\n8:         self.name = name\n9:         self._completed = False\n10:         self._current_attempt = None\n11: \n12:     @property\n13:     def completed(self):\n14:         return self._completed\n15: \n16:     def mark_completed(self):\n17:         self._completed = True\n18: \n19:     @property\n20:     def completion_message(self):\n21:         return None\n22: \n23:     def begin_activation(self):\n24:         \"\"\"Prepare this feature instance for an initial or later command stage.\"\"\"\n25:         self._completed = False\n26:         self._current_attempt = None\n27: \n28:     @property\n29:     def current_attempt(self):\n30:         return self._current_attempt\n31: \n32:     @property\n33:     def current_command(self):\n34:         return self._current_attempt.spec if self._current_attempt else None\n35: \n36:     @property\n37:     def command_output(self):\n38:         return bytes(self._current_attempt.output) if self._current_attempt else b\"\"\n39: \n40:     def activate(self):\n41:         self.commander.feature_complete(self)\n42: \n43:     def on_command_dispatched(self, attempt):\n44:         self._current_attempt = attempt\n45: \n46:     def on_output(self, output):\n47:         return False\n48: \n49:     def on_command_executed(self, command, state):\n50:         pass\n51: \n52:     def on_block_complete(self):\n53:         self.commander.feature_complete(self)\n54: \n55:     def on_session_loss(self, attempt):\n56:         return attempt.spec.session_loss\n57: \n58:     def on_context_loss(self, attempt):\n59:         \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n60:         return attempt.spec.context_loss\n61: \n62:     def reversal_blocks(self):\n63:         \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n64:         return []\n65: \n66:     def undo(self):\n67:         \"\"\"Return a feature stage that reverses this completed feature.\"\"\"\n68:         return _FeatureUndo(self.vm, self.commander, self)\n69: \n70:     @property\n71:     def file_path(self):\n72:         \"\"\"Return the optional file path watched for this feature.\"\"\"\n73:         return None\n74: \n75:     def on_file_detected(self, path):\n76:         pass\n77: \n78:     def on_file_deleted(self, path):\n79:         pass\n80: \n81:     def on_file_modified(self, path):\n82:         pass\n83: \n84: \n85: class StaticFeature(Feature):\n86:     \"\"\"A feature whose command blocks are known when it is constructed.\"\"\"\n87: \n88:     def __init__(self, vm, commander, name, blocks, on_complete=None):\n89:         super().__init__(vm, commander, name)\n90:         self._blocks = list(blocks)\n91:         self._on_complete = on_complete\n92: \n93:     def activate(self):\n94:         self._submit_next()\n95: \n96:     def _submit_next(self):\n97:         if self._blocks:\n98:             self.commander.submit_block(self, self._blocks.pop(0))\n99:             return\n100:         if self._on_complete:\n101:             self._on_complete()\n102:         self.commander.feature_complete(self)\n103: \n104:     def on_block_complete(self):\n105:         self._submit_next()\n106: \n107: \n108: class _FeatureUndo(StaticFeature):\n109:     \"\"\"A scheduled reversal stage created by ``Feature.undo``.\"\"\"\n110: \n111:     def __init__(self, vm, commander, target):\n112:         super().__init__(vm, commander, f\"undo-{target.name}\", ())\n113:         self._target = target\n114: \n115:     def activate(self):\n116:         if not self._target.completed:\n117:             raise RuntimeError(f\"Cannot undo incomplete feature {self._target.name}\")\n118:         self._blocks = list(self._target.reversal_blocks())\n119:         super().activate()\n\n(End of file - total 119 lines)\n</content>",
    "title": "source/head/fortinet/common/features/base.py",
    "metadata": {
      "preview": "\"\"\"Shared feature lifecycle primitives.\"\"\"\n\n\nclass Feature:\n    def __init__(self, vm, commander, name):\n        self.vm = vm\n        self.commander = commander\n        self.name = name\n        self._completed = False\n        self._current_attempt = None\n\n    @property\n    def completed(self):\n        return self._completed\n\n    def mark_completed(self):\n        self._completed = True\n\n    @property\n    def completion_message(self):",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/base.py",
        "text": "\"\"\"Shared feature lifecycle primitives.\"\"\"\n\n\nclass Feature:\n    def __init__(self, vm, commander, name):\n        self.vm = vm\n        self.commander = commander\n        self.name = name\n        self._completed = False\n        self._current_attempt = None\n\n    @property\n    def completed(self):\n        return self._completed\n\n    def mark_completed(self):\n        self._completed = True\n\n    @property\n    def completion_message(self):\n        return None\n\n    def begin_activation(self):\n        \"\"\"Prepare this feature instance for an initial or later command stage.\"\"\"\n        self._completed = False\n        self._current_attempt = None\n\n    @property\n    def current_attempt(self):\n        return self._current_attempt\n\n    @property\n    def current_command(self):\n        return self._current_attempt.spec if self._current_attempt else None\n\n    @property\n    def command_output(self):\n        return bytes(self._current_attempt.output) if self._current_attempt else b\"\"\n\n    def activate(self):\n        self.commander.feature_complete(self)\n\n    def on_command_dispatched(self, attempt):\n        self._current_attempt = attempt\n\n    def on_output(self, output):\n        return False\n\n    def on_command_executed(self, command, state):\n        pass\n\n    def on_block_complete(self):\n        self.commander.feature_complete(self)\n\n    def on_session_loss(self, attempt):\n        return attempt.spec.session_loss\n\n    def on_context_loss(self, attempt):\n        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n        return attempt.spec.context_loss\n\n    def reversal_blocks(self):\n        \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n        return []\n\n    def undo(self):\n        \"\"\"Return a feature stage that reverses this completed feature.\"\"\"\n        return _FeatureUndo(self.vm, self.commander, self)\n\n    @property\n    def file_path(self):\n        \"\"\"Return the optional file path watched for this feature.\"\"\"\n        return None\n\n    def on_file_detected(self, path):\n        pass\n\n    def on_file_deleted(self, path):\n        pass\n\n    def on_file_modified(self, path):\n        pass\n\n\nclass StaticFeature(Feature):\n    \"\"\"A feature whose command blocks are known when it is constructed.\"\"\"\n\n    def __init__(self, vm, commander, name, blocks, on_complete=None):\n        super().__init__(vm, commander, name)\n        self._blocks = list(blocks)\n        self._on_complete = on_complete\n\n    def activate(self):\n        self._submit_next()\n\n    def _submit_next(self):\n        if self._blocks:\n            self.commander.submit_block(self, self._blocks.pop(0))\n            return\n        if self._on_complete:\n            self._on_complete()\n        self.commander.feature_complete(self)\n\n    def on_block_complete(self):\n        self._submit_next()\n\n\nclass _FeatureUndo(StaticFeature):\n    \"\"\"A scheduled reversal stage created by ``Feature.undo``.\"\"\"\n\n    def __init__(self, vm, commander, target):\n        super().__init__(vm, commander, f\"undo-{target.name}\", ())\n        self._target = target\n\n    def activate(self):\n        if not self._target.completed:\n            raise RuntimeError(f\"Cannot undo incomplete feature {self._target.name}\")\n        self._blocks = list(self._target.reversal_blocks())\n        super().activate()",
        "lineStart": 1,
        "lineEnd": 119,
        "totalLines": 119,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716409930,
      "end": 1793716409934
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/license.py"
}

Output

<path>/source/head/fortinet/common/features/license.py</path>
<type>file</type>
<content>
1: """VM license installation feature."""
2: 
3: import os
4: import re
5: import time
6: 
7: from ..cli_commands import CommandSequence, CommandSpec, SessionLossAction
8: from ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState
9: from ..env import get_env
10: 
11: from .base import Feature
12: 
13: 
14: DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60
15: LICENSE_STATUS_POLL_INTERVAL_SECONDS = 2
16: LICENSE_SETTLE_SECONDS = 3
17: LICENSE_WAIT_STATUSES = {"pending"}
18: LICENSE_GRACE_PERIOD_STATUS = "grace period"
19: LOG_LICENSE_STATUS_OUTPUT_ENV = "FOS_LOG_LICENSE_STATUS_OUTPUT"
20: 
21: # FortiOS does not print a single success message for "execute restore
22: # vmlicense"; the only failure signature is "license install failed"
23: # (e.g. "VM license install failed."). Everything else is success.
24: LICENSE_FAILURE_PATTERN = re.compile(rb"(?mi)license install failed")
25: 
26: 
27: def license_status_timeout_seconds():
28:     value = get_env("FOS_LICENSE_STATUS_TIMEOUT_SECONDS")
29:     if not value:
30:         return DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS
31:     return int(value)
32: 
33: 
34: def wait_for_valid_license():
35:     return get_env("FOS_WAIT_FOR_VALID_LICENSE", "false").strip().lower() == "true"
36: 
37: 
38: class SetLicense(Feature):
39:     """Install a license without waiting for online validation.
40: 
41:     FortiOS license restore reboots the VM and can reset parts of management
42:     networking.  Online validation must be polled only after post-license
43:     management repair has run.
44:     """
45: 
46:     def __init__(self, vm, commander):
47:         super().__init__(vm, commander, "setup-license")
48:         self._enabled = os.path.exists("/tftpboot/appliance.lic")
49:         self._tftp_server_ip = vm.mgmt_gw_ipv4
50:         self._phase = "restore"
51:         self._wait_for_prompt = False
52: 
53:     def activate(self):
54:         if not self._enabled:
55:             self.commander.feature_complete(self)
56:             return
57:         self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)
58:         self._submit_restore()
59: 
60:     def _submit_restore(self):
61:         # CMD_PROMPT must complete the restore too: when the install fails
62:         # FortiOS prints the failure and returns to the prompt without ever
63:         # asking for confirmation, which would otherwise wedge the block.
64:         self.commander.submit_block(self, CommandSequence("restore-license", [
65:             CommandSpec(
66:                 f"exe restore vmlicense tftp appliance.lic {self._tftp_server_ip}",
67:                 completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),
68:                 capture_output=True,
69:                 session_loss=SessionLossAction.CONTINUE,
70:             ),
71:         ]))
72: 
73:     def on_command_executed(self, command, state):
74:         self._check_for_failure(command)
75:         if self._phase == "restore" and state == FOSCliState.CONFIRMATION:
76:             self._phase = "restore-confirmed"
77:             self.commander.submit_block(self, CommandSequence("confirm-license", [
78:                 CommandSpec(
79:                     "y",
80:                     completion_states=(FOSCliState.REBOOTING,),
81:                     session_loss=SessionLossAction.CONTINUE,
82:                 ),
83:             ]))
84:             return
85:         if self._phase == "restore-confirmed" and state == FOSCliState.REBOOTING:
86:             self._phase = "wait-prompt"
87:             self._wait_for_prompt = True
88:             return
89:         # The restore completed somewhere other than the confirmation
90:         # prompt (a plain prompt instead): the install failed before
91:         # confirmation. The failure check above already raised on a "fail"
92:         # word, so fall through to wait-prompt rather than wedging the
93:         # block.
94:         self._phase = "wait-prompt"
95:         self._wait_for_prompt = True
96: 
97:     def on_output(self, output):
98:         """Raise on a failure reported while a license command runs.
99: 
100:         The confirmation is completed by the reboot, not by the command
101:         prompt that returns right after "y" and before the reboot starts, so
102:         a failed install would otherwise only surface once the command
103:         completed. Watch the streaming output instead.
104:         """
105:         if self._phase in ("restore", "restore-confirmed"):
106:             output = bytes(output)
107:             if LICENSE_FAILURE_PATTERN.search(output):
108:                 raise RuntimeError(
109:                     f"VM license install failed: {output!r}"
110:                 )
111:         return False
112: 
113:     def _check_for_failure(self, command):
114:         output = bytes(command.output)
115:         if LICENSE_FAILURE_PATTERN.search(output):
116:             raise RuntimeError(
117:                 f"VM license install failed: {output!r}"
118:             )
119: 
120:     def on_block_complete(self):
121:         if self._phase in ("restore", "restore-confirmed"):
122:             return
123:         if self._phase == "wait-prompt":
124:             if self._wait_for_prompt:
125:                 self._wait_for_prompt = False
126:                 return
127:             self._phase = "done"
128:         if self._phase == "done":
129:             self.commander.feature_complete(self)
130: 
131:     def on_session_loss(self, attempt):
132:         if attempt.spec.session_loss == SessionLossAction.CONTINUE:
133:             self._phase = "wait-prompt"
134:             self._wait_for_prompt = True
135:         return attempt.spec.session_loss
136: 
137: 
138: class WaitForLicenseValidation(Feature):
139:     """Poll FortiOS until the restored license validates or times out."""
140: 
141:     def __init__(self, vm, commander):
142:         super().__init__(vm, commander, "license-validation")
143:         self._enabled = os.path.exists("/tftpboot/appliance.lic")
144:         self._logger = commander.logger
145:         self._deadline = None
146:         self._next_poll = None
147:         self._phase = "idle"
148:         self._status = None
149:         self._status_outputs_logged = set()
150:         self._standard_output_active = False
151:         self._settle_until = 0
152: 
153:     @property
154:     def status(self):
155:         return self._status
156: 
157:     @property
158:     def valid(self):
159:         return self._status is not None and self._status.lower() == "valid"
160: 
161:     def activate(self):
162:         if not self._enabled:
163:             self.commander.feature_complete(self)
164:             return
165:         self._deadline = time.monotonic() + license_status_timeout_seconds()
166:         self._phase = "polling"
167:         self._next_poll = time.monotonic()
168: 
169:     def on_command_executed(self, command, state):
170:         output = bytes(command.output)
171:         status = self._license_status(output)
172:         self._log_status_output(output, status)
173:         normalized_status = status.lower() if status else None
174:         if (
175:             not status
176:             or normalized_status in LICENSE_WAIT_STATUSES
177:             or (
178:                 normalized_status == LICENSE_GRACE_PERIOD_STATUS
179:                 and wait_for_valid_license()
180:             )
181:         ):
182:             previous_status = self._status.lower() if self._status else None
183:             self._status = status
184:             if normalized_status != previous_status:
185:                 self._logger.info(
186:                     "License status is %s; continuing validation polls",
187:                     status or "unavailable",
188:                 )
189:             if time.monotonic() >= self._deadline:
190:                 raise RuntimeError(
191:                     "VM license validation timed out with status "
192:                     f"{status or 'unavailable'}"
193:                 )
194:             self._next_poll = time.monotonic() + LICENSE_STATUS_POLL_INTERVAL_SECONDS
195:             return
196:         self._status = status
197:         if normalized_status == LICENSE_GRACE_PERIOD_STATUS:
198:             self._logger.info(
199:                 "Accepting license status %s without waiting for Valid",
200:                 status,
201:             )
202:             self._finish_validation()
203:             return
204:         if status.lower() != "valid":
205:             raise RuntimeError(
206:                 f"VM license validation failed: status {status}"
207:             )
208:         self._logger.info(f"License status changed to {status}")
209:         self._finish_validation()
210: 
211:     def _finish_validation(self):
212:         self._phase = "done"
213:         self._settle_until = time.monotonic() + LICENSE_SETTLE_SECONDS
214: 
215:     @staticmethod
216:     def _license_status(output):
217:         match = re.search(rb"(?mi)^License Status:\s*(.+?)\s*\r?$", output)
218:         if not match:
219:             match = re.search(rb"(?mi)^License:\s*(.+?)\s*\r?$", output)
220:         return match.group(1).decode(errors="replace").strip() if match else None
221: 
222:     def _log_status_output(self, output, status):
223:         if get_env(
224:             LOG_LICENSE_STATUS_OUTPUT_ENV, "false"
225:         ).strip().lower() != "true":
226:             return
227:         normalized_status = status.lower() if status else None
228:         if normalized_status in self._status_outputs_logged:
229:             return
230:         self._status_outputs_logged.add(normalized_status)
231:         self._logger.info(
232:             "Captured get system status output for license status %s:\n%s",
233:             status or "unavailable",
234:             output.decode(errors="replace").rstrip(),
235:         )
236: 
237:     def on_block_complete(self):
238:         if self._phase != "done":
239:             return
240:         if time.monotonic() < self._settle_until:
241:             return
242:         self.commander.feature_complete(self)
243: 
244:     def tick(self):
245:         now = time.monotonic()
246:         if self._phase == "done":
247:             if now >= self._settle_until:
248:                 self.commander.feature_complete(self)
249:             return
250:         if self._phase != "polling" or self._next_poll is None:
251:             return
252:         if now >= self._deadline:
253:             raise RuntimeError(
254:                 "VM license validation timed out with status "
255:                 f"{self._status or 'unavailable'}"
256:             )
257:         if now >= self._next_poll and not self.commander.busy:
258:             self._next_poll = None
259:             if self._standard_output_active:
260:                 self._submit_status_poll()
261:             else:
262:                 self._standard_output_active = True
263:                 self.commander.with_standard_output(self, self._submit_status_poll)
264: 
265:     def _submit_status_poll(self):
266:         self.commander.submit_block(self, CommandSequence("license-validation", [
267:             CommandSpec("get system status", capture_output=True, suppress_output=True),
268:         ]))

(End of file - total 268 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d4567c001TbTT8mbQiGAsMr",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4326c001skDYJshLglEpG0",
  "callID": "call_a0d3d8505a864225a3f2242e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/license.py"
    },
    "output": "<path>/source/head/fortinet/common/features/license.py</path>\n<type>file</type>\n<content>\n1: \"\"\"VM license installation feature.\"\"\"\n2: \n3: import os\n4: import re\n5: import time\n6: \n7: from ..cli_commands import CommandSequence, CommandSpec, SessionLossAction\n8: from ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState\n9: from ..env import get_env\n10: \n11: from .base import Feature\n12: \n13: \n14: DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60\n15: LICENSE_STATUS_POLL_INTERVAL_SECONDS = 2\n16: LICENSE_SETTLE_SECONDS = 3\n17: LICENSE_WAIT_STATUSES = {\"pending\"}\n18: LICENSE_GRACE_PERIOD_STATUS = \"grace period\"\n19: LOG_LICENSE_STATUS_OUTPUT_ENV = \"FOS_LOG_LICENSE_STATUS_OUTPUT\"\n20: \n21: # FortiOS does not print a single success message for \"execute restore\n22: # vmlicense\"; the only failure signature is \"license install failed\"\n23: # (e.g. \"VM license install failed.\"). Everything else is success.\n24: LICENSE_FAILURE_PATTERN = re.compile(rb\"(?mi)license install failed\")\n25: \n26: \n27: def license_status_timeout_seconds():\n28:     value = get_env(\"FOS_LICENSE_STATUS_TIMEOUT_SECONDS\")\n29:     if not value:\n30:         return DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS\n31:     return int(value)\n32: \n33: \n34: def wait_for_valid_license():\n35:     return get_env(\"FOS_WAIT_FOR_VALID_LICENSE\", \"false\").strip().lower() == \"true\"\n36: \n37: \n38: class SetLicense(Feature):\n39:     \"\"\"Install a license without waiting for online validation.\n40: \n41:     FortiOS license restore reboots the VM and can reset parts of management\n42:     networking.  Online validation must be polled only after post-license\n43:     management repair has run.\n44:     \"\"\"\n45: \n46:     def __init__(self, vm, commander):\n47:         super().__init__(vm, commander, \"setup-license\")\n48:         self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n49:         self._tftp_server_ip = vm.mgmt_gw_ipv4\n50:         self._phase = \"restore\"\n51:         self._wait_for_prompt = False\n52: \n53:     def activate(self):\n54:         if not self._enabled:\n55:             self.commander.feature_complete(self)\n56:             return\n57:         self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)\n58:         self._submit_restore()\n59: \n60:     def _submit_restore(self):\n61:         # CMD_PROMPT must complete the restore too: when the install fails\n62:         # FortiOS prints the failure and returns to the prompt without ever\n63:         # asking for confirmation, which would otherwise wedge the block.\n64:         self.commander.submit_block(self, CommandSequence(\"restore-license\", [\n65:             CommandSpec(\n66:                 f\"exe restore vmlicense tftp appliance.lic {self._tftp_server_ip}\",\n67:                 completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),\n68:                 capture_output=True,\n69:                 session_loss=SessionLossAction.CONTINUE,\n70:             ),\n71:         ]))\n72: \n73:     def on_command_executed(self, command, state):\n74:         self._check_for_failure(command)\n75:         if self._phase == \"restore\" and state == FOSCliState.CONFIRMATION:\n76:             self._phase = \"restore-confirmed\"\n77:             self.commander.submit_block(self, CommandSequence(\"confirm-license\", [\n78:                 CommandSpec(\n79:                     \"y\",\n80:                     completion_states=(FOSCliState.REBOOTING,),\n81:                     session_loss=SessionLossAction.CONTINUE,\n82:                 ),\n83:             ]))\n84:             return\n85:         if self._phase == \"restore-confirmed\" and state == FOSCliState.REBOOTING:\n86:             self._phase = \"wait-prompt\"\n87:             self._wait_for_prompt = True\n88:             return\n89:         # The restore completed somewhere other than the confirmation\n90:         # prompt (a plain prompt instead): the install failed before\n91:         # confirmation. The failure check above already raised on a \"fail\"\n92:         # word, so fall through to wait-prompt rather than wedging the\n93:         # block.\n94:         self._phase = \"wait-prompt\"\n95:         self._wait_for_prompt = True\n96: \n97:     def on_output(self, output):\n98:         \"\"\"Raise on a failure reported while a license command runs.\n99: \n100:         The confirmation is completed by the reboot, not by the command\n101:         prompt that returns right after \"y\" and before the reboot starts, so\n102:         a failed install would otherwise only surface once the command\n103:         completed. Watch the streaming output instead.\n104:         \"\"\"\n105:         if self._phase in (\"restore\", \"restore-confirmed\"):\n106:             output = bytes(output)\n107:             if LICENSE_FAILURE_PATTERN.search(output):\n108:                 raise RuntimeError(\n109:                     f\"VM license install failed: {output!r}\"\n110:                 )\n111:         return False\n112: \n113:     def _check_for_failure(self, command):\n114:         output = bytes(command.output)\n115:         if LICENSE_FAILURE_PATTERN.search(output):\n116:             raise RuntimeError(\n117:                 f\"VM license install failed: {output!r}\"\n118:             )\n119: \n120:     def on_block_complete(self):\n121:         if self._phase in (\"restore\", \"restore-confirmed\"):\n122:             return\n123:         if self._phase == \"wait-prompt\":\n124:             if self._wait_for_prompt:\n125:                 self._wait_for_prompt = False\n126:                 return\n127:             self._phase = \"done\"\n128:         if self._phase == \"done\":\n129:             self.commander.feature_complete(self)\n130: \n131:     def on_session_loss(self, attempt):\n132:         if attempt.spec.session_loss == SessionLossAction.CONTINUE:\n133:             self._phase = \"wait-prompt\"\n134:             self._wait_for_prompt = True\n135:         return attempt.spec.session_loss\n136: \n137: \n138: class WaitForLicenseValidation(Feature):\n139:     \"\"\"Poll FortiOS until the restored license validates or times out.\"\"\"\n140: \n141:     def __init__(self, vm, commander):\n142:         super().__init__(vm, commander, \"license-validation\")\n143:         self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n144:         self._logger = commander.logger\n145:         self._deadline = None\n146:         self._next_poll = None\n147:         self._phase = \"idle\"\n148:         self._status = None\n149:         self._status_outputs_logged = set()\n150:         self._standard_output_active = False\n151:         self._settle_until = 0\n152: \n153:     @property\n154:     def status(self):\n155:         return self._status\n156: \n157:     @property\n158:     def valid(self):\n159:         return self._status is not None and self._status.lower() == \"valid\"\n160: \n161:     def activate(self):\n162:         if not self._enabled:\n163:             self.commander.feature_complete(self)\n164:             return\n165:         self._deadline = time.monotonic() + license_status_timeout_seconds()\n166:         self._phase = \"polling\"\n167:         self._next_poll = time.monotonic()\n168: \n169:     def on_command_executed(self, command, state):\n170:         output = bytes(command.output)\n171:         status = self._license_status(output)\n172:         self._log_status_output(output, status)\n173:         normalized_status = status.lower() if status else None\n174:         if (\n175:             not status\n176:             or normalized_status in LICENSE_WAIT_STATUSES\n177:             or (\n178:                 normalized_status == LICENSE_GRACE_PERIOD_STATUS\n179:                 and wait_for_valid_license()\n180:             )\n181:         ):\n182:             previous_status = self._status.lower() if self._status else None\n183:             self._status = status\n184:             if normalized_status != previous_status:\n185:                 self._logger.info(\n186:                     \"License status is %s; continuing validation polls\",\n187:                     status or \"unavailable\",\n188:                 )\n189:             if time.monotonic() >= self._deadline:\n190:                 raise RuntimeError(\n191:                     \"VM license validation timed out with status \"\n192:                     f\"{status or 'unavailable'}\"\n193:                 )\n194:             self._next_poll = time.monotonic() + LICENSE_STATUS_POLL_INTERVAL_SECONDS\n195:             return\n196:         self._status = status\n197:         if normalized_status == LICENSE_GRACE_PERIOD_STATUS:\n198:             self._logger.info(\n199:                 \"Accepting license status %s without waiting for Valid\",\n200:                 status,\n201:             )\n202:             self._finish_validation()\n203:             return\n204:         if status.lower() != \"valid\":\n205:             raise RuntimeError(\n206:                 f\"VM license validation failed: status {status}\"\n207:             )\n208:         self._logger.info(f\"License status changed to {status}\")\n209:         self._finish_validation()\n210: \n211:     def _finish_validation(self):\n212:         self._phase = \"done\"\n213:         self._settle_until = time.monotonic() + LICENSE_SETTLE_SECONDS\n214: \n215:     @staticmethod\n216:     def _license_status(output):\n217:         match = re.search(rb\"(?mi)^License Status:\\s*(.+?)\\s*\\r?$\", output)\n218:         if not match:\n219:             match = re.search(rb\"(?mi)^License:\\s*(.+?)\\s*\\r?$\", output)\n220:         return match.group(1).decode(errors=\"replace\").strip() if match else None\n221: \n222:     def _log_status_output(self, output, status):\n223:         if get_env(\n224:             LOG_LICENSE_STATUS_OUTPUT_ENV, \"false\"\n225:         ).strip().lower() != \"true\":\n226:             return\n227:         normalized_status = status.lower() if status else None\n228:         if normalized_status in self._status_outputs_logged:\n229:             return\n230:         self._status_outputs_logged.add(normalized_status)\n231:         self._logger.info(\n232:             \"Captured get system status output for license status %s:\\n%s\",\n233:             status or \"unavailable\",\n234:             output.decode(errors=\"replace\").rstrip(),\n235:         )\n236: \n237:     def on_block_complete(self):\n238:         if self._phase != \"done\":\n239:             return\n240:         if time.monotonic() < self._settle_until:\n241:             return\n242:         self.commander.feature_complete(self)\n243: \n244:     def tick(self):\n245:         now = time.monotonic()\n246:         if self._phase == \"done\":\n247:             if now >= self._settle_until:\n248:                 self.commander.feature_complete(self)\n249:             return\n250:         if self._phase != \"polling\" or self._next_poll is None:\n251:             return\n252:         if now >= self._deadline:\n253:             raise RuntimeError(\n254:                 \"VM license validation timed out with status \"\n255:                 f\"{self._status or 'unavailable'}\"\n256:             )\n257:         if now >= self._next_poll and not self.commander.busy:\n258:             self._next_poll = None\n259:             if self._standard_output_active:\n260:                 self._submit_status_poll()\n261:             else:\n262:                 self._standard_output_active = True\n263:                 self.commander.with_standard_output(self, self._submit_status_poll)\n264: \n265:     def _submit_status_poll(self):\n266:         self.commander.submit_block(self, CommandSequence(\"license-validation\", [\n267:             CommandSpec(\"get system status\", capture_output=True, suppress_output=True),\n268:         ]))\n\n(End of file - total 268 lines)\n</content>",
    "title": "source/head/fortinet/common/features/license.py",
    "metadata": {
      "preview": "\"\"\"VM license installation feature.\"\"\"\n\nimport os\nimport re\nimport time\n\nfrom ..cli_commands import CommandSequence, CommandSpec, SessionLossAction\nfrom ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState\nfrom ..env import get_env\n\nfrom .base import Feature\n\n\nDEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60\nLICENSE_STATUS_POLL_INTERVAL_SECONDS = 2\nLICENSE_SETTLE_SECONDS = 3\nLICENSE_WAIT_STATUSES = {\"pending\"}\nLICENSE_GRACE_PERIOD_STATUS = \"grace period\"\nLOG_LICENSE_STATUS_OUTPUT_ENV = \"FOS_LOG_LICENSE_STATUS_OUTPUT\"\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/license.py",
        "text": "\"\"\"VM license installation feature.\"\"\"\n\nimport os\nimport re\nimport time\n\nfrom ..cli_commands import CommandSequence, CommandSpec, SessionLossAction\nfrom ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState\nfrom ..env import get_env\n\nfrom .base import Feature\n\n\nDEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60\nLICENSE_STATUS_POLL_INTERVAL_SECONDS = 2\nLICENSE_SETTLE_SECONDS = 3\nLICENSE_WAIT_STATUSES = {\"pending\"}\nLICENSE_GRACE_PERIOD_STATUS = \"grace period\"\nLOG_LICENSE_STATUS_OUTPUT_ENV = \"FOS_LOG_LICENSE_STATUS_OUTPUT\"\n\n# FortiOS does not print a single success message for \"execute restore\n# vmlicense\"; the only failure signature is \"license install failed\"\n# (e.g. \"VM license install failed.\"). Everything else is success.\nLICENSE_FAILURE_PATTERN = re.compile(rb\"(?mi)license install failed\")\n\n\ndef license_status_timeout_seconds():\n    value = get_env(\"FOS_LICENSE_STATUS_TIMEOUT_SECONDS\")\n    if not value:\n        return DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS\n    return int(value)\n\n\ndef wait_for_valid_license():\n    return get_env(\"FOS_WAIT_FOR_VALID_LICENSE\", \"false\").strip().lower() == \"true\"\n\n\nclass SetLicense(Feature):\n    \"\"\"Install a license without waiting for online validation.\n\n    FortiOS license restore reboots the VM and can reset parts of management\n    networking.  Online validation must be polled only after post-license\n    management repair has run.\n    \"\"\"\n\n    def __init__(self, vm, commander):\n        super().__init__(vm, commander, \"setup-license\")\n        self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n        self._tftp_server_ip = vm.mgmt_gw_ipv4\n        self._phase = \"restore\"\n        self._wait_for_prompt = False\n\n    def activate(self):\n        if not self._enabled:\n            self.commander.feature_complete(self)\n            return\n        self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)\n        self._submit_restore()\n\n    def _submit_restore(self):\n        # CMD_PROMPT must complete the restore too: when the install fails\n        # FortiOS prints the failure and returns to the prompt without ever\n        # asking for confirmation, which would otherwise wedge the block.\n        self.commander.submit_block(self, CommandSequence(\"restore-license\", [\n            CommandSpec(\n                f\"exe restore vmlicense tftp appliance.lic {self._tftp_server_ip}\",\n                completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),\n                capture_output=True,\n                session_loss=SessionLossAction.CONTINUE,\n            ),\n        ]))\n\n    def on_command_executed(self, command, state):\n        self._check_for_failure(command)\n        if self._phase == \"restore\" and state == FOSCliState.CONFIRMATION:\n            self._phase = \"restore-confirmed\"\n            self.commander.submit_block(self, CommandSequence(\"confirm-license\", [\n                CommandSpec(\n                    \"y\",\n                    completion_states=(FOSCliState.REBOOTING,),\n                    session_loss=SessionLossAction.CONTINUE,\n                ),\n            ]))\n            return\n        if self._phase == \"restore-confirmed\" and state == FOSCliState.REBOOTING:\n            self._phase = \"wait-prompt\"\n            self._wait_for_prompt = True\n            return\n        # The restore completed somewhere other than the confirmation\n        # prompt (a plain prompt instead): the install failed before\n        # confirmation. The failure check above already raised on a \"fail\"\n        # word, so fall through to wait-prompt rather than wedging the\n        # block.\n        self._phase = \"wait-prompt\"\n        self._wait_for_prompt = True\n\n    def on_output(self, output):\n        \"\"\"Raise on a failure reported while a license command runs.\n\n        The confirmation is completed by the reboot, not by the command\n        prompt that returns right after \"y\" and before the reboot starts, so\n        a failed install would otherwise only surface once the command\n        completed. Watch the streaming output instead.\n        \"\"\"\n        if self._phase in (\"restore\", \"restore-confirmed\"):\n            output = bytes(output)\n            if LICENSE_FAILURE_PATTERN.search(output):\n                raise RuntimeError(\n                    f\"VM license install failed: {output!r}\"\n                )\n        return False\n\n    def _check_for_failure(self, command):\n        output = bytes(command.output)\n        if LICENSE_FAILURE_PATTERN.search(output):\n            raise RuntimeError(\n                f\"VM license install failed: {output!r}\"\n            )\n\n    def on_block_complete(self):\n        if self._phase in (\"restore\", \"restore-confirmed\"):\n            return\n        if self._phase == \"wait-prompt\":\n            if self._wait_for_prompt:\n                self._wait_for_prompt = False\n                return\n            self._phase = \"done\"\n        if self._phase == \"done\":\n            self.commander.feature_complete(self)\n\n    def on_session_loss(self, attempt):\n        if attempt.spec.session_loss == SessionLossAction.CONTINUE:\n            self._phase = \"wait-prompt\"\n            self._wait_for_prompt = True\n        return attempt.spec.session_loss\n\n\nclass WaitForLicenseValidation(Feature):\n    \"\"\"Poll FortiOS until the restored license validates or times out.\"\"\"\n\n    def __init__(self, vm, commander):\n        super().__init__(vm, commander, \"license-validation\")\n        self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n        self._logger = commander.logger\n        self._deadline = None\n        self._next_poll = None\n        self._phase = \"idle\"\n        self._status = None\n        self._status_outputs_logged = set()\n        self._standard_output_active = False\n        self._settle_until = 0\n\n    @property\n    def status(self):\n        return self._status\n\n    @property\n    def valid(self):\n        return self._status is not None and self._status.lower() == \"valid\"\n\n    def activate(self):\n        if not self._enabled:\n            self.commander.feature_complete(self)\n            return\n        self._deadline = time.monotonic() + license_status_timeout_seconds()\n        self._phase = \"polling\"\n        self._next_poll = time.monotonic()\n\n    def on_command_executed(self, command, state):\n        output = bytes(command.output)\n        status = self._license_status(output)\n        self._log_status_output(output, status)\n        normalized_status = status.lower() if status else None\n        if (\n            not status\n            or normalized_status in LICENSE_WAIT_STATUSES\n            or (\n                normalized_status == LICENSE_GRACE_PERIOD_STATUS\n                and wait_for_valid_license()\n            )\n        ):\n            previous_status = self._status.lower() if self._status else None\n            self._status = status\n            if normalized_status != previous_status:\n                self._logger.info(\n                    \"License status is %s; continuing validation polls\",\n                    status or \"unavailable\",\n                )\n            if time.monotonic() >= self._deadline:\n                raise RuntimeError(\n                    \"VM license validation timed out with status \"\n                    f\"{status or 'unavailable'}\"\n                )\n            self._next_poll = time.monotonic() + LICENSE_STATUS_POLL_INTERVAL_SECONDS\n            return\n        self._status = status\n        if normalized_status == LICENSE_GRACE_PERIOD_STATUS:\n            self._logger.info(\n                \"Accepting license status %s without waiting for Valid\",\n                status,\n            )\n            self._finish_validation()\n            return\n        if status.lower() != \"valid\":\n            raise RuntimeError(\n                f\"VM license validation failed: status {status}\"\n            )\n        self._logger.info(f\"License status changed to {status}\")\n        self._finish_validation()\n\n    def _finish_validation(self):\n        self._phase = \"done\"\n        self._settle_until = time.monotonic() + LICENSE_SETTLE_SECONDS\n\n    @staticmethod\n    def _license_status(output):\n        match = re.search(rb\"(?mi)^License Status:\\s*(.+?)\\s*\\r?$\", output)\n        if not match:\n            match = re.search(rb\"(?mi)^License:\\s*(.+?)\\s*\\r?$\", output)\n        return match.group(1).decode(errors=\"replace\").strip() if match else None\n\n    def _log_status_output(self, output, status):\n        if get_env(\n            LOG_LICENSE_STATUS_OUTPUT_ENV, \"false\"\n        ).strip().lower() != \"true\":\n            return\n        normalized_status = status.lower() if status else None\n        if normalized_status in self._status_outputs_logged:\n            return\n        self._status_outputs_logged.add(normalized_status)\n        self._logger.info(\n            \"Captured get system status output for license status %s:\\n%s\",\n            status or \"unavailable\",\n            output.decode(errors=\"replace\").rstrip(),\n        )\n\n    def on_block_complete(self):\n        if self._phase != \"done\":\n            return\n        if time.monotonic() < self._settle_until:\n            return\n        self.commander.feature_complete(self)\n\n    def tick(self):\n        now = time.monotonic()\n        if self._phase == \"done\":\n            if now >= self._settle_until:\n                self.commander.feature_complete(self)\n            return\n        if self._phase != \"polling\" or self._next_poll is None:\n            return\n        if now >= self._deadline:\n            raise RuntimeError(\n                \"VM license validation timed out with status \"\n                f\"{self._status or 'unavailable'}\"\n            )\n        if now >= self._next_poll and not self.commander.busy:\n            self._next_poll = None\n            if self._standard_output_active:\n                self._submit_status_poll()\n            else:\n                self._standard_output_active = True\n                self.commander.with_standard_output(self, self._submit_status_poll)\n\n    def _submit_status_poll(self):\n        self.commander.submit_block(self, CommandSequence(\"license-validation\", [\n            CommandSpec(\"get system status\", capture_output=True, suppress_output=True),\n        ]))",
        "lineStart": 1,
        "lineEnd": 268,
        "totalLines": 268,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716409984,
      "end": 1793716409997
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d4569d0019rPbRLLc94yNiM",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4326c001skDYJshLglEpG0",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 37700,
    "input": 5557,
    "output": 112,
    "reasoning": 543,
    "cache": {
      "read": 31488,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d4326c001skDYJshLglEpG0",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716400748,
    "completed": 1793716410016
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 37700,
    "input": 5557,
    "output": 112,
    "reasoning": 543,
    "cache": {
      "read": 31488,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 17
step-start
{
  "type": "step-start",
  "id": "prt_1a1d45e24001nGEDRwzACeFEbx",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d456a5001o3bO2lt54vLSLy"
}
Reasoning
Now I understand the Data/expect semantics:

- On match: consumed bytes (up to match end) removed from buffer, returned as `Data(consumed)` with NO discard callback. So consumers don't need to discard matched output; it's already gone.
- On timeout: full unmatched buffer returned as Data with `_discard_prefix` callback; buffer retains it unless a consumer discards.

`CommandAttempt.on_output` captures and discards when `capture_output or closes_scope`. So a capturing command's `attempt.output` gets bytes exactly once per byte, because:
- unmatched output (timeout) → driver forwards once → attempt.on_output appends + discards from buffer.
- matched output → expect already removed those bytes from buffer; Data has no discard callback; attempt.on_output appends bytes(output) and calls output.discard(data) — with no callback, discard just sets discarded=True, harmless.

But wait — driver line 109-113: `if output and not matched: commander.on_output(output); output = type(output)(b"")`. Then `_process_state(state, output)` with empty Data. For state UNKNOWN/TN_TIMEOUT, commander.on_state is called with empty Data → on_output(empty) returns early. Good, no duplication.

But what about matched output? In `process_state`, `if output and not matched:` — matched output is NOT forwarded to commander.on_output directly; instead `_process_state(state, output)` → `commander.on_state(state, output)` → inside on_state: `self.on_output(output)` (line 292). So matched Data reaches on_output once via on_state. Good.

However: there's a subtlety in `process_state` for unmatched: commander.on_output is called BEFORE the state handler; on_state is then called with empty Data. But for CMD_PROMPT matched, on_state gets full Data and calls on_output. Both paths invoke inflight/active feature on_output. What about the case where output is unmatched but state is UNKNOWN/TN_TIMEOUT and there IS an inflight capturing command: attempt.on_output appends and discards → buffer cleared. Good.

What if inflight exists but is NOT capturing (capture_output=False, not closes_scope) and active feature's on_output returns False → `_inspect_output`: discards only if `_recovering`. Otherwise bytes stay in buffer. Next expect timeout exposes them again → commander.on_output → again nothing consumes → buffer grows. With a capturing inflight they'd be captured. Non-capturing command with streaming junk output: buffer grows to 1MB limit → RuntimeError. That's by design ("Terminal buffer exceeded ... without being consumed"). Pre-existing behavior presumably.

Now the duplicate-processing concern: `received_new_data` flag distinguishes. SetLicense.on_output: `if LICENSE_FAILURE_PATTERN.search(output)` — output here is the Data view. For timeout Data it's the full retained buffer (could include previously searched bytes) — re-searching is idempotent for detection (raising on same failure), so no correctness issue. It returns False always unless raising. So no duplicate consumption issue for license.

Now the remaining suspicion from handoff: (c) `_cleanup_retries` keyed by `id(spec)` — fine as analyzed; specs are alive in `_cleanup`/attempt while keyed. But there is one wrinkle: `_complete_inflight` pops `self._cleanup_retries.pop(id(attempt.spec), None)` on success, and `submit_block`... doesn't clear cleanup retries. `continue_after_error` clears them. If a cleanup spec object is dropped after an error without `continue_after_error` (e.g., `_handle_work_error` raised → process dies; best-effort → `continue_after_error` clears). So bounded. Fine — probably not worth a finding, or P4 at most.

(d) `_complete_inflight` ordering: context-loss check happens BEFORE `_validate_completion`. For `closes_scope` commands (`next`/`end`), `_command_may_change_context` returns True for "next"/"end", so a context change after a successful `next` is NOT treated as context loss (correct — scope close legitimately changes context). For a FAILED `next` ("Command fail. Return code -542"), FortiOS stays in the edit context → prompt context unchanged → falls to `_validate_completion` → raises. Test `test_closing_failure_with_same_prompt_still_ejects` covers this. So ordering is fine.

But hold on: what if the failure output arrives and the prompt context is also extracted differently? The test at line 77-91: prompt(commander, "port1", b"Command fail. Return code -61.\r\n") → the Data contains failure text + prompt. `_extract_prompt_context` extracts from output — context "port1". `_prompt_context` was already... hmm, in that test the first prompt had context port1. The second prompt with same context → `_prompt_context` unchanged → `_prompt_context_changed` False → validate → failure detected. Good.

Now, one more potential issue: `_prompt_context_changed` requires before/after not None. `_prompt_context` initial None. On the very first CMD_PROMPT, `_extract_prompt_context` may return `()` (top-level) if the prompt matched the pattern with no context group. If the prompt output doesn't match CLI_PROMPT_CONTEXT_PATTERN (e.g. hostname mismatch with BOOTSTRAP_HOSTNAME_REGEX?), `_extract_prompt_context` returns None → `_prompt_context` retains old value. When is context loss missed? If the after-prompt can't be parsed... but CMD_PROMPT state pattern uses the same PROMPT_CONTEXT_REGEX with hostname — if the driver recognized CMD_PROMPT, the commander's pattern should also match (same regexes: BOOTSTRAP_HOSTNAME_REGEX + context). Driver's CMD_PROMPT pattern = `^[ \t]*` + hostname + PROMPT_CONTEXT_REGEX + `[ \t]*[#$][ \t]*\r?$`. Commander's CLI_PROMPT_CONTEXT_PATTERN = `^[ \t]*` + BOOTSTRAP_HOSTNAME_REGEX + `(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$`. If driver uses set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX) — same. So consistent.

Edge: what if prompt context changes but `after` is None (extraction failed)? Then context loss undetected → command considered complete → next command dispatched into wrong scope. But extraction None requires the pattern not matching, while driver matched CMD_PROMPT. With identical regexes, extraction should match. Unless the CMD_PROMPT match came from a different pattern index... driver's `_state_patterns` includes all FOS_CLI_STATE_PATTERNS; CMD_PROMPT index match wins by earliest end. If another pattern matched earlier... it's the earliest-match rule. OK.

Now `_handle_session_loss` during `_in_context_reset` (abort dispatched, session lost): sets `_in_context_reset = False` and returns, keeping `_replay_context_target`. Then reconnect → prompt → `_dispatch_next` → `_restore_replay_context` checks context again. Bounded by `_context_reset_attempted`? Note `_restart_active_block` resets `_context_reset_attempted = False`, but session loss during context reset does NOT reset it. So after reconnect, `_restore_replay_context` still has target set and `_context_reset_attempted` possibly True from a previous failed abort → immediately errors "Unable to restore CLI context" without trying abort again. Hmm — is that a bug? Consider: context loss → restart block → target set, `_context_reset_attempted=False` → dispatch abort → abort completes at CMD_PROMPT but context still not target → `_context_reset_attempted=True` → error. OK bounded.

Alternative: abort dispatched, session lost before abort completes → `_in_context_reset` False, `_context_reset_attempted` still False → after reconnect, dispatch abort again. Fine.

But: abort completes successfully (returns to top-level), then session lost during... no.

What about session loss during context reset where the abort DID succeed but the reconnect login dropped into a different scope? After reconnect, `_restore_replay_context` → context != target → `_context_reset_attempted` False → dispatch abort again (one more try). Fine.

OK. Now, `test_session_loss_during_context_reset_resumes_after_login` verifies this.

Next: `submit_block` resets `_replay_context_target = None` and `_context_reset_attempted = False`. But `_recovery_retries = {}` also reset per block. `_dispatch_command` reads retry count from `_recovery_retries.get(block_index, 0)`.

Potential issue: `_restart_active_block` sets `self._pending = deque(self._active_commands)` and replays. But block_index recomputed from `_active_commands - _pending` — correct.

Now — the concern about `_complete_inflight` for MULTILINE_PROMPT / CONFIRMATION states: `attempt.prompt_context_after = self._prompt_context` — for CONFIRMATION, prompt_context is whatever was last extracted (unchanged). `_prompt_context_changed` requires state == CMD_PROMPT anyway (checked in _complete_inflight line 435: `if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt)`). OK.

Now, `on_prompt_echo`: driver `_process_state` calls `commander.on_prompt_echo(output)` for CMD_PROMPT_ECHO. on_prompt_echo calls on_output(output).discarded check → if not discarded, writes b"\r" to get a clean prompt. For CMD_PROMPT_ECHO the Data has no discard callback (matched path), so discard() sets flag True without callback... wait: matched Data has `_discard_callback=None`. `discard()` with no callback → sets discarded=True, returns. So `self.on_output(output).discarded` — if inflight captures (attempt.on_output discards → discarded=True), returns early. Otherwise falls through to write b"\r". But the echoed bytes were already removed from buffer (matched path). So "requesting a clean prompt" is by design — echo output indicates junk after prompt. Fine.

Hmm wait, there's a real subtlety: in on_state, `self.on_output(output)` is called for EVERY state including PROVIDE_USERNAME etc. If inflight is capturing and the login prompts echo... fine.

Now let me check the diff to identify what exactly changed, to focus findings on PR-introduced issues. I need to re-read diff.txt. It's large; read in chunks. Actually the handoff says diff was fully reviewed, but I don't have its content in context. Key changed files: cli_commands.py (context_loss/continuation/closes_scope/_flatten_quoted_lines), fos_commander.py (scope-commit failure, context tracking, bounded recovery), terminal.py (timeout full-buffer semantics, received_new_data, TRACE_LEVEL), fos_cli_driver.py (stall detection, KernelPanicError, credential recovery), common.py (patterns, TRACE_LEVEL), features (credentials, base, startup_config, pki), launch.py (KernelPanicError), tests, READMEs.

Let me read the diff to ground claims. It's ~? lines. Read in two chunks of 1200.
The `Data` semantics are now clear: matched output is already consumed by `expect`, and the driver forwards each timeout view exactly once, so `attempt.output` sees each byte once. Next, I'll re-read the diff to ground which behaviors are PR-introduced, and check the remaining tests and docs.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 1250,
  "offset": 1
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py
2: index ea16d0f..1af3f4d 100644
3: --- a/fortinet/common/cli_commands.py
4: +++ b/fortinet/common/cli_commands.py
5: @@ -12,46 +12,72 @@ class SessionLossAction(Enum):
6:      CONTINUE = auto()
7:      VALIDATE = auto()
8:      FAIL = auto()
9:  
10:  
11: +class ContextLossAction(Enum):
12: +    RESTART_BLOCK = auto()
13: +    FAIL = auto()
14: +
15: +
16:  @dataclass(frozen=True, init=False)
17:  class CommandSpec:
18:      line: str
19:      completion_states: tuple = ()
20:      capture_output: bool = False
21:      suppress_output: bool = False
22:      session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK
23:      expected_completion_state: object = None
24:      fail_on_error: bool = False
25: +    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK
26: +    continuation: bool = False
27:  
28:      def __init__(self, line, completion_states=(), capture_output=False,
29:                   suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,
30: -                 expected_completion_state=None, fail_on_error=False):
31: +                 expected_completion_state=None, fail_on_error=False,
32: +                 context_loss=None, continuation=False):
33:          object.__setattr__(self, "line", line)
34:          object.__setattr__(self, "completion_states", completion_states)
35:          object.__setattr__(self, "capture_output", capture_output)
36:          object.__setattr__(self, "suppress_output", suppress_output)
37:          object.__setattr__(self, "session_loss", session_loss)
38:          object.__setattr__(self, "expected_completion_state", expected_completion_state)
39:          object.__setattr__(self, "fail_on_error", fail_on_error)
40: +        object.__setattr__(self, "continuation", continuation)
41: +        if context_loss is None:
42: +            # Commands that must not replay after logout must not replay after
43: +            # an unexpected scope exit either. Features can override this policy.
44: +            context_loss = (
45: +                ContextLossAction.RESTART_BLOCK
46: +                if session_loss == SessionLossAction.RESTART_BLOCK
47: +                else ContextLossAction.FAIL
48: +            )
49: +        object.__setattr__(self, "context_loss", context_loss)
50:          self.__post_init__()
51:  
52:      def __post_init__(self):
53:          if "\r" in self.line or "\n" in self.line:
54:              raise ValueError("CLI commands must contain exactly one line")
55:  
56: +    @property
57: +    def closes_scope(self):
58: +        return not self.continuation and self.line.strip().lower() in {"next", "end"}
59: +
60:  
61:  @dataclass
62:  class CommandAttempt:
63:      spec: CommandSpec
64:      number: int
65:      session_epoch: int
66:      output: bytearray = field(default_factory=bytearray)
67: +    prompt_context_before: tuple | None = None
68: +    prompt_context_after: tuple | None = None
69: +    block_index: int | None = None
70: +    retry_count: int = 0
71:  
72:      def on_output(self, output):
73: -        if not self.spec.capture_output:
74: +        if not (self.spec.capture_output or self.spec.closes_scope):
75:              return False
76:          data = bytes(output)
77:          self.output.extend(data)
78:          output.discard(data)
79:          return True
80: @@ -69,11 +95,11 @@ class Scope:
81:      @property
82:      def close_line(self):
83:          raise NotImplementedError
84:  
85:      def flatten(self):
86: -        commands = [CommandSpec(self.open_line)]
87: +        commands = flatten_commands(self.open_line)
88:          for child in self.children:
89:              commands.extend(flatten_commands(child))
90:          commands.append(CommandSpec(self.close_line))
91:          return commands
92:  
93: @@ -107,49 +133,43 @@ class SetValue:
94:          self.fail_on_error = fail_on_error
95:          self.validate_prompt = validate_prompt
96:  
97:      def flatten(self):
98:          lines = str(self.value).strip().splitlines() or [""]
99: -        if len(lines) == 1:
100: -            return [CommandSpec(
101: -                f'set {self.field} "{lines[0]}"',
102: -                capture_output=True,
103: -                expected_completion_state=(
104: -                    FOSCliState.CMD_PROMPT if self.validate_prompt else None
105: -                ),
106: -                fail_on_error=self.fail_on_error,
107: -            )]
108: -
109: -        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
110: -        commands = [CommandSpec(
111: -            f'set {self.field} "{lines[0]}',
112: -            completion_states=both_prompts,
113: -            capture_output=True,
114: -            expected_completion_state=(
115: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None
116: -            ),
117: -            fail_on_error=self.fail_on_error,
118: -        )]
119: -        commands.extend(CommandSpec(
120: -            line,
121: -            completion_states=both_prompts,
122: -            capture_output=True,
123: -            expected_completion_state=(
124: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None
125: -            ),
126: -            fail_on_error=self.fail_on_error,
127: -        ) for line in lines[1:-1])
128: +        lines[0] = f'set {self.field} "{lines[0]}'
129: +        lines[-1] += '"'
130: +        return _flatten_quoted_lines(
131: +            lines, fail_on_error=self.fail_on_error,
132: +            validate_prompt=self.validate_prompt,
133: +        )
134: +
135: +
136: +def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):
137: +    """Send a logical command one line per continuation prompt, without re-quoting."""
138: +    commands = []
139: +    for index, line in enumerate(lines):
140: +        last_line = index == len(lines) - 1
141: +        expected = (
142: +            FOSCliState.CMD_PROMPT if last_line
143: +            else FOSCliState.MULTILINE_PROMPT
144: +        )
145: +        completion_states = ()
146: +        if len(lines) > 1:
147: +            completion_states = (
148: +                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)
149: +                if last_line else
150: +                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
151: +            )
152:          commands.append(CommandSpec(
153: -            f'{lines[-1]}"',
154: -            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),
155: +            line,
156: +            completion_states=completion_states,
157:              capture_output=True,
158: -            expected_completion_state=(
159: -                FOSCliState.CMD_PROMPT if self.validate_prompt else None
160: -            ),
161: -            fail_on_error=self.fail_on_error,
162: +            expected_completion_state=expected if validate_prompt else None,
163: +            fail_on_error=fail_on_error,
164: +            continuation=index > 0,
165:          ))
166: -        return commands
167: +    return commands
168:  
169:  
170:  class CommandSequence:
171:      """An unscoped workflow container; it does not emit CLI framing."""
172:  
173: @@ -165,10 +185,12 @@ class CommandSequence:
174:  
175:  
176:  def flatten_commands(value):
177:      """Flatten command containers and wrap plain CLI lines with defaults."""
178:      if isinstance(value, str):
179: +        if "\n" in value:
180: +            return _flatten_quoted_lines(value.split("\n"))
181:          return [CommandSpec(value)]
182:      if isinstance(value, CommandSpec):
183:          return [value]
184:      if isinstance(value, (Scope, CommandSequence, SetValue)):
185:          return value.flatten()
186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py
187: index 4ffb817..b020deb 100644
188: --- a/fortinet/common/common.py
189: +++ b/fortinet/common/common.py
190: @@ -21,10 +21,11 @@ class FOSCliState(IntEnum):
191:      CURRENT_PASSWORD = auto()
192:      CONFIRMATION = auto()
193:      CHANGE_PASSWORD_CONFIRM = auto()
194:      MORE_PROMPT = auto()
195:      MULTILINE_PROMPT = auto()
196: +    KERNEL_PANIC = auto()
197:      UNKNOWN = auto()  # Non-patterns from here on.
198:      TN_TIMEOUT = auto()
199:  
200:  
201:  GENERIC_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+"
202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (
203:  )
204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb"(?mi)Do you want to continue\?"
205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb"(?mi)^Confirm Password:[ \t]*"
206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb"--More--\s*"
207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb"(?m)^>[ \t]*\r?$"
208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (
209: +    rb"(?mi)^Kernel panic(?: - not syncing)?:[^\r\n]*\r?\n"
210: +    rb"CPU: [0-9]+ PID: [0-9]+ Comm: [^\r\n]+"
211: +)
212:  
213:  DEF_POLICY_COMPLIANT_PASSWORD = "FortinetFOS1!"
214:  DEFAULT_USERNAME = "admin"
215:  DEFAULT_PASSWORD = DEFAULT_USERNAME
216:  
217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py
218: index 83ebc9b..5dd906a 100644
219: --- a/fortinet/common/features/base.py
220: +++ b/fortinet/common/features/base.py
221: @@ -53,10 +53,14 @@ class Feature:
222:          self.commander.feature_complete(self)
223:  
224:      def on_session_loss(self, attempt):
225:          return attempt.spec.session_loss
226:  
227: +    def on_context_loss(self, attempt):
228: +        """Choose whether the commander may replay this interrupted block."""
229: +        return attempt.spec.context_loss
230: +
231:      def reversal_blocks(self):
232:          """Return command blocks that completely reverse this feature's work."""
233:          return []
234:  
235:      def undo(self):
236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py
237: index b8bc7de..af39225 100644
238: --- a/fortinet/common/features/credentials.py
239: +++ b/fortinet/common/features/credentials.py
240: @@ -1,14 +1,15 @@
241:  """Administrator bootstrap feature."""
242:  
243: -from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction
244: +from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction
245: +from ..common import FOSCliState
246:  
247:  from .base import StaticFeature
248:  
249:  
250:  class CredentialsFeature(StaticFeature):
251: -    """Configure the administrator and change credentials after password loss."""
252: +    """Configure the administrator, then log out and authenticate again."""
253:  
254:      def __init__(self, vm, commander):
255:          self._activate_after_admin_commit = False
256:          self._desired_credentials_activated = False
257:          self._password_change_committed = False
258: @@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):
259:                  fail_on_error=True,
260:              ))
261:          super().__init__(vm, commander, "admin", [
262:              ConfigBlock("system password-policy", ["set status disable"]),
263:              ConfigBlock("system admin", [EditBlock(credentials.username, admin_children)]),
264: +            CommandSequence("admin-relogin", [CommandSpec(
265: +                "exit",
266: +                session_loss=SessionLossAction.CONTINUE,
267: +                capture_output=True,
268: +                fail_on_error=True,
269: +                # A successful logout takes the session-loss path. Returning
270: +                # straight to a CLI prompt must not count as verification.
271: +                expected_completion_state=FOSCliState.PROVIDE_USERNAME,
272: +            )]),
273:          ], on_complete=lambda: self._activate_desired_credentials())
274:  
275: +    def on_command_dispatched(self, attempt):
276: +        if attempt.spec.line == "exit":
277: +            self._activate_desired_credentials()
278: +        super().on_command_dispatched(attempt)
279: +
280:      def on_session_loss(self, attempt):
281: +        if attempt.spec.line == "exit":
282: +            # The commander resumes this block only at the authenticated CLI
283: +            # prompt. Clear the logout command so it cannot be replayed.
284: +            return SessionLossAction.CONTINUE
285:          if self._is_password_command(attempt.spec.line):
286:              self._activate_desired_credentials()
287:              self._activate_after_admin_commit = False
288:              return SessionLossAction.CONTINUE
289: +        if self._activate_after_admin_commit and attempt.spec.line == "next":
290: +            # Some releases log out during the commit instead of returning
291: +            # its CLI prompt. Authenticate with the committed password.
292: +            self._activate_desired_credentials()
293: +            self._activate_after_admin_commit = False
294: +            self._password_change_committed = True
295: +            return SessionLossAction.CONTINUE
296:          if self._password_change_committed:
297:              # FortiOS may log out as the admin edit closes. The password
298:              # command and `next` have already committed the new credentials,
299:              # so replaying this block would use the previous password again.
300:              return SessionLossAction.CONTINUE
301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py
302: index 96a90d3..a5f0de7 100644
303: --- a/fortinet/common/features/pki.py
304: +++ b/fortinet/common/features/pki.py
305: @@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):
306:      @staticmethod
307:      def _config_item_block(scope, name, children):
308:          # A configuration attempt is deliberately best-effort: the feature
309:          # must be able to inspect the result and fall back to the TFTP import
310:          # path when a firmware release does not expose this config tree.  If
311: -        # these wrapper commands keep ``fail_on_error`` enabled, the commander
312: -        # raises before ``on_command_executed`` can record the failed config
313: -        # attempt and select the fallback.
314: +        # opening commands keep ``fail_on_error`` enabled, the commander raises
315: +        # before ``on_command_executed`` can select that fallback. A return-code
316: +        # failure from `next` or `end` is always fatal to the feature: the
317: +        # commander checks scope commits even when fail_on_error is disabled.
318:          def config_command(line):
319:              return CommandSpec(line, capture_output=True, fail_on_error=False)
320:  
321:          return CommandSequence(f"{scope}-{name}", [
322:              config_command(f"config {scope}"),
323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py
324: index e404fc8..cb99aa4 100644
325: --- a/fortinet/common/features/startup_config.py
326: +++ b/fortinet/common/features/startup_config.py
327: @@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):
328:              "FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL"
329:          )
330:      return filtered
331:  
332:  
333: +def _startup_config_commands(config):
334: +    """Yield logical CLI commands while retaining quoted newlines verbatim."""
335: +    pending = []
336: +    quote = None
337: +    start_line = None
338: +    for number, raw_line in enumerate(config, start=1):
339: +        # Text mode normalizes file line endings. Only remove the delimiter;
340: +        # whitespace and comment/scope-looking lines inside quotes are data.
341: +        line = raw_line.removesuffix("\n")
342: +        if not pending:
343: +            line = line.lstrip()
344: +            if not line or line.startswith("#"):
345: +                continue
346: +            start_line = number
347: +
348: +        escaped = False
349: +        for character in line:
350: +            if escaped:
351: +                escaped = False
352: +            elif character == "\\":
353: +                escaped = True
354: +            elif character == quote:
355: +                quote = None
356: +            elif quote is None and character in {"'", '"'}:
357: +                quote = character
358: +
359: +        if quote is not None or escaped:
360: +            pending.append(line)
361: +            continue
362: +        pending.append(line.rstrip())
363: +        yield "\n".join(pending)
364: +        pending.clear()
365: +
366: +    if pending:
367: +        reason = "unterminated quoted string" if quote else "unfinished line continuation"
368: +        raise ValueError(
369: +            f"Startup config malformed. {reason} starting on line {start_line}."
370: +        )
371: +
372: +
373:  def parse_startup_config(path):
374:      roots = []
375:      stack = []
376:      with open(path) as config:
377: -        for raw_line in config:
378: -            line = raw_line.strip()
379: -            if not line or line.startswith("#"):
380: -                continue
381: +        for line in _startup_config_commands(config):
382:              if line.startswith("config "):
383:                  node = ConfigBlock(line[7:])
384:                  (stack[-1].children if stack else roots).append(node)
385:                  stack.append(node)
386:              elif line.startswith("edit "):
387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py
388: index fa34100..b527816 100644
389: --- a/fortinet/common/fos_cli_driver.py
390: +++ b/fortinet/common/fos_cli_driver.py
391: @@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10
392:  EXPECT_TIMEOUT_SECONDS = 1
393:  UNKNOWN_STALL_SECONDS = 30
394:  UNKNOWN_STALL_NEWLINE_LIMIT = 3
395:  
396:  
397: +class KernelPanicError(RuntimeError):
398: +    """Raised when the guest kernel reports a panic on the serial console."""
399: +
400: +
401:  class FOSCliDriver:
402:      """Owns serial reads and delegates command dispatch to the commander."""
403:  
404:      def __init__(
405:          self,
406: @@ -65,10 +69,11 @@ class FOSCliDriver:
407:              FOSCliState.CMD_PROMPT: self._command_prompt,
408:              FOSCliState.CMD_PROMPT_ECHO: None,
409:              FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,
410:              FOSCliState.LIC_FAIL: self._license_failed,
411:              FOSCliState.TN_TIMEOUT: self._timeout,
412: +            FOSCliState.KERNEL_PANIC: self._kernel_panic,
413:              FOSCliState.UNKNOWN: self._unknown,
414:          }
415:  
416:      @property
417:      def state_patterns(self):
418: @@ -145,11 +150,14 @@ class FOSCliDriver:
419:  
420:      def _next_state(self):
421:          index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)
422:          if match:
423:              return FOSCliState(index), output, True
424: -        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False
425: +        # A timeout exposes retained bytes too. Only fresh input should reset
426: +        # the unknown-output stall timer; an unchanged buffer is still idle.
427: +        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT
428: +        return state, output, False
429:  
430:      def _handle_state(self, state):
431:          handler = self._state_handlers.get(state)
432:          if handler:
433:              try:
434: @@ -254,10 +262,14 @@ class FOSCliDriver:
435:  
436:      def _unknown(self):
437:          if self._last_known_state == FOSCliState.REBOOTING:
438:              self._idle_spins += 1
439:  
440: +    @staticmethod
441: +    def _kernel_panic():
442: +        raise KernelPanicError("Kernel panic detected on serial console")
443: +
444:      def _note_unknown_output(self):
445:          self._unknown_started_at = time.monotonic()
446:  
447:      def _recover_unknown_stall(self):
448:          if self._unknown_started_at is None:
449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py
450: index 26312cf..86b1be6 100644
451: --- a/fortinet/common/fos_commander.py
452: +++ b/fortinet/common/fos_commander.py
453: @@ -10,24 +10,29 @@ from .cli_commands import (
454:      CleanupAction,
455:      CommandAttempt,
456:      CommandSequence,
457:      CommandSpec,
458:      ConfigBlock,
459: +    ContextLossAction,
460:      SessionLossAction,
461:      flatten_commands,
462:  )
463:  from .terminal import Data
464: -from .common import FOSCliState, TRACE_LEVEL
465: +from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL
466:  
467:  DISPATCHABLE_COMPLETION_STATES = {
468:      FOSCliState.CMD_PROMPT,
469:      FOSCliState.CONFIRMATION,
470:      FOSCliState.MULTILINE_PROMPT,
471:  }
472:  COMMAND_FAILURE_PATTERN = re.compile(
473:      rb"(?mi)^\s*Command fail\.\s*Return code\s+(-?\d+)"
474:  )
475: +CLI_PROMPT_CONTEXT_PATTERN = re.compile(
476: +    rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX
477: +    + rb"(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$"
478: +)
479:  
480:  
481:  @dataclass
482:  class _StandardOutputContext:
483:      feature: object
484: @@ -35,10 +40,11 @@ class _StandardOutputContext:
485:      phase: str = "inspect"
486:      restore: bool = False
487:  
488:  
489:  class FOSCommander:
490: +    MAX_COMMAND_RECOVERY_RETRIES = 1
491:      _CONSOLE_OUTPUT_PATTERN = re.compile(rb"(?mi)^\s*set output (more|standard)\s*\r?$")
492:      _CONSOLE_INSPECT_LINE = "show full-configuration system console"
493:      _CONSOLE_STANDARD_LINE = "set output standard"
494:  
495:      def __init__(self, terminal, logger, continue_on_error=False):
496: @@ -65,23 +71,37 @@ class FOSCommander:
497:          self._start_time = datetime.datetime.now()
498:          self._continue_on_error = continue_on_error
499:          self._pending_feature_error = None
500:          self._current_state = None
501:          self._callback_failed = False
502: +        self._prompt_context = None
503: +        self._block_prompt_context = None
504: +        self._recovery_retries = {}
505: +        self._cleanup_retries = {}
506: +        self._replay_context_target = None
507: +        self._context_reset_attempted = False
508: +        self._in_context_reset = False
509:  
510:      def _call_feature(self, callback, *args):
511:          """Run a feature callback and apply best-effort policy at this boundary."""
512:          try:
513:              return callback(*args)
514:          except Exception as error:
515: -            if not self._continue_on_error:
516: -                raise
517: -            self.logger.exception("Bootstrap feature callback failed")
518: -            self._pending_feature_error = error
519: -            self._callback_failed = True
520: +            self._handle_work_error(error, from_callback=True)
521:              return None
522:  
523: +    def _handle_work_error(self, error, *, from_callback=False):
524: +        """Apply the configured failure policy after feature/recovery decisions."""
525: +        if not self._continue_on_error:
526: +            raise error
527: +        if from_callback:
528: +            self.logger.exception("Bootstrap feature callback failed")
529: +        else:
530: +            self.logger.error("Bootstrap work failed: %s", error, exc_info=error)
531: +        self._pending_feature_error = error
532: +        self._callback_failed = True
533: +
534:      def _recover_feature_error(self, *, at_idle_prompt=False):
535:          error = self._pending_feature_error
536:          if error is None or (
537:              self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
538:          ):
539: @@ -143,10 +163,13 @@ class FOSCommander:
540:              self._inflight = None
541:              self._suppression.close()
542:              self._suppression = ExitStack()
543:  
544:          self._in_cleanup = False
545: +        self._replay_context_target = None
546: +        self._in_context_reset = False
547: +        self._cleanup_retries.clear()
548:          self._feature_errors.append((failed_name, str(error)))
549:          return failed_name
550:  
551:      def record_feature_error(self, name, error):
552:          """Record a recoverable bootstrap problem without stopping the queue."""
553: @@ -184,10 +207,14 @@ class FOSCommander:
554:          if self.busy:
555:              raise RuntimeError("Cannot replace an active command block")
556:          commands = tuple(flatten_commands(block))
557:          self._active_commands = commands
558:          self._pending = deque(commands)
559: +        self._block_prompt_context = self._prompt_context
560: +        self._recovery_retries = {}
561: +        self._replay_context_target = None
562: +        self._context_reset_attempted = False
563:  
564:      def feature_complete(self, feature):
565:          if feature is not self._active_feature:
566:              return
567:          if self.busy:
568: @@ -242,10 +269,18 @@ class FOSCommander:
569:  
570:      def on_state(self, state, output):
571:          """Called by the driver for every recognized serial state."""
572:          self._current_state = state
573:          self._callback_failed = False
574: +        if state == FOSCliState.CMD_PROMPT:
575: +            context = self._extract_prompt_context(output)
576: +            if context is not None:
577: +                self._prompt_context = context
578: +            # Some releases return directly to a usable prompt after login,
579: +            # without a Welcome banner. The prompt also ends session recovery.
580: +            self._authenticated_once = True
581: +            self._recovering = False
582:          if self._pending_feature_error is not None:
583:              if state == FOSCliState.CMD_PROMPT:
584:                  self._recover_feature_error()
585:              elif state == FOSCliState.SESSION_LOST:
586:                  self._session_epoch += 1
587: @@ -275,13 +310,10 @@ class FOSCommander:
588:              return
589:          if state == FOSCliState.CREDENTIAL_ACCEPTED:
590:              self._authenticated_once = True
591:              self._recovering = False
592:              return
593: -        if state == FOSCliState.CMD_PROMPT:
594: -            self._authenticated_once = True
595: -
596:          if self._inflight and state in (
597:              self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
598:          ):
599:              self._complete_inflight(state)
600:              return
601: @@ -345,28 +377,41 @@ class FOSCommander:
602:          self._call_feature(self._active_feature.begin_activation)
603:          if self._pending_feature_error is None:
604:              self._call_feature(self._active_feature.activate)
605:  
606:      def _dispatch_next(self):
607: -        if self._inflight or self._recovering:
608: +        if self._inflight or self._recovering or self._pending_feature_error is not None:
609: +            return
610: +        if not self._restore_replay_context():
611:              return
612:          if not self._cleanup and self._active_feature is None:
613:              self._activate_next_feature()
614:              if self._active_feature is None:
615:                  return
616:          if self._cleanup:
617:              spec = self._cleanup.popleft()
618:              self._in_cleanup = True
619: +            block_index = None
620:          elif not self._pending:
621:              self._call_feature(self._active_feature.on_block_complete)
622:              return
623:          else:
624:              spec = self._pending.popleft()
625:              self._in_cleanup = False
626: +            block_index = len(self._active_commands) - len(self._pending) - 1
627: +        self._dispatch_command(spec, block_index)
628: +
629: +    def _dispatch_command(self, spec, block_index=None):
630:          self._attempt_number += 1
631:          self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)
632: -        if self._active_feature:
633: +        self._inflight.prompt_context_before = self._prompt_context
634: +        self._inflight.block_index = block_index
635: +        self._inflight.retry_count = (
636: +            self._cleanup_retries.get(id(spec), 0)
637: +            if self._in_cleanup else self._recovery_retries.get(block_index, 0)
638: +        )
639: +        if self._active_feature and not self._in_context_reset:
640:              self._call_feature(self._active_feature.on_command_dispatched, self._inflight)
641:              if self._pending_feature_error is not None:
642:                  return
643:          if spec.suppress_output:
644:              self._suppression.enter_context(self.terminal.suppress_output())
645: @@ -380,12 +425,34 @@ class FOSCommander:
646:      def _complete_inflight(self, state):
647:          attempt = self._inflight
648:          self._inflight = None
649:          self._suppression.close()
650:          self._suppression = ExitStack()
651: -        self._validate_completion(attempt, state)
652: +        attempt.prompt_context_after = self._prompt_context
653: +        if self._in_context_reset:
654: +            self._in_context_reset = False
655: +            self._dispatch_next()
656: +            return
657: +        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
658: +            self._handle_context_loss(attempt)
659: +            if self._pending_feature_error is not None:
660: +                self._recover_feature_error()
661: +            else:
662: +                self._dispatch_next()
663: +            return
664: +        try:
665: +            self._validate_completion(attempt, state)
666: +        except RuntimeError as error:
667: +            if state != FOSCliState.CMD_PROMPT:
668: +                # An interactive prompt cannot safely advance to another feature.
669: +                raise
670: +            self._handle_work_error(error)
671: +            if self._pending_feature_error is not None:
672: +                self._recover_feature_error()
673: +            return
674:          if self._in_cleanup:
675: +            self._cleanup_retries.pop(id(attempt.spec), None)
676:              self._in_cleanup = False
677:              self._dispatch_next()
678:              return
679:          if self._is_standard_output_command(attempt.spec):
680:              self._complete_standard_output_command(attempt)
681: @@ -404,24 +471,105 @@ class FOSCommander:
682:          if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:
683:              self._dispatch_next()
684:  
685:      @staticmethod
686:      def _validate_completion(attempt, state):
687: -        if attempt.spec.fail_on_error and (
688: +        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (
689:              failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))
690:          ):
691:              raise RuntimeError(
692: -                "FortiOS command failed "
693: +                f"FortiOS command {attempt.spec.line!r} failed "
694:                  f"(return code {failure.group(1).decode()})"
695:              )
696:          expected = attempt.spec.expected_completion_state
697:          if expected is not None and state != expected:
698:              raise RuntimeError(
699:                  "CLI command completed at unexpected prompt: "
700:                  f"expected {expected.name}, received {state.name}"
701:              )
702:  
703: +    def _prompt_context_changed(self, attempt):
704: +        before = attempt.prompt_context_before
705: +        after = attempt.prompt_context_after
706: +        return (
707: +            before is not None
708: +            and after is not None
709: +            and before != after
710: +            and not self._command_may_change_context(attempt.spec)
711: +        )
712: +
713: +    def _handle_context_loss(self, attempt):
714: +        reason = (
715: +            "CLI context changed from "
716: +            f"{self._format_prompt_context(attempt.prompt_context_before)} to "
717: +            f"{self._format_prompt_context(attempt.prompt_context_after)}"
718: +        )
719: +        if self._in_cleanup:
720: +            self._handle_work_error(RuntimeError(
721: +                f"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay"
722: +            ))
723: +            return
724: +        action = self._call_feature(self._active_feature.on_context_loss, attempt)
725: +        if self._pending_feature_error is not None:
726: +            return
727: +        if action == ContextLossAction.RESTART_BLOCK:
728: +            self._restart_active_block(attempt, reason)
729: +        elif action == ContextLossAction.FAIL:
730: +            self._handle_work_error(RuntimeError(
731: +                f"{reason} during {attempt.spec.line!r}; feature declined replay"
732: +            ))
733: +        else:
734: +            self._handle_work_error(ValueError(f"Unsupported context-loss action: {action!r}"))
735: +
736: +    def _restore_replay_context(self):
737: +        """Unwind a surviving partial scope once before replaying its openers."""
738: +        target = self._replay_context_target
739: +        if target is None:
740: +            return True
741: +        if self._prompt_context == target:
742: +            self._replay_context_target = None
743: +            return True
744: +        if self._context_reset_attempted:
745: +            self._handle_work_error(RuntimeError(
746: +                "Unable to restore CLI context before replay: expected "
747: +                f"{self._format_prompt_context(target)}, received "
748: +                f"{self._format_prompt_context(self._prompt_context or ())}"
749: +            ))
750: +            if self._pending_feature_error is not None:
751: +                self._recover_feature_error()
752: +            return False
753: +        self._context_reset_attempted = True
754: +        self._in_context_reset = True
755: +        self._dispatch_command(CommandSpec("abort", suppress_output=True))
756: +        return False
757: +
758: +    @staticmethod
759: +    def _command_may_change_context(spec):
760: +        if spec.continuation:
761: +            return False
762: +        command = spec.line.strip().lower()
763: +        return (
764: +            command.startswith(("config ", "edit "))
765: +            or command in {"next", "end", "abort", "exit", "quit"}
766: +            or command == "set vdom-mode multi-vdom"
767: +        )
768: +
769: +    @staticmethod
770: +    def _extract_prompt_context(output):
771: +        data = bytes(output)
772: +        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))
773: +        if not matches:
774: +            return None
775: +        return tuple(
776: +            item.decode(errors="replace")
777: +            for item in re.findall(rb"\(([^)]*)\)", matches[-1].group("context"))
778: +        )
779: +
780: +    @staticmethod
781: +    def _format_prompt_context(context):
782: +        return " ".join(f"({item})" for item in context) or "<top-level>"
783: +
784:      def _is_standard_output_command(self, spec):
785:          context = self._standard_output_context
786:          return context is not None and (
787:              spec.line == self._CONSOLE_INSPECT_LINE
788:              or (context.phase == "set-standard" and not self._pending)
789: @@ -466,11 +614,24 @@ class FOSCommander:
790:              return
791:          attempt = self._inflight
792:          self._inflight = None
793:          self._suppression.close()
794:          self._suppression = ExitStack()
795: +        if self._in_context_reset:
796: +            # Login may itself restore the target scope. The pending replay
797: +            # stays bounded by the original command's recovery allowance.
798: +            self._in_context_reset = False
799: +            return
800:          if self._in_cleanup:
801: +            retries = self._cleanup_retries.get(id(attempt.spec), 0)
802: +            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
803: +                self._handle_work_error(RuntimeError(
804: +                    f"Session lost repeatedly during cleanup {attempt.spec.line!r}; "
805: +                    "retry limit reached"
806: +                ))
807: +                return
808: +            self._cleanup_retries[id(attempt.spec)] = retries + 1
809:              self._cleanup.appendleft(attempt.spec)
810:              self._in_cleanup = False
811:              return
812:          self._schedule_feature_cleanup(self._active_feature, "interruption")
813:          action = self._call_feature(
814: @@ -481,24 +642,39 @@ class FOSCommander:
815:              return
816:          self.logger.info(
817:              f"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}"
818:          )
819:          action_handlers = {
820: -            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),
821: +            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(
822: +                attempt, "session lost"
823: +            ),
824:              SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),
825:              SessionLossAction.CONTINUE: lambda: self._pending.clear(),
826: -            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),
827: +            SessionLossAction.FAIL: lambda: self._handle_work_error(
828: +                RuntimeError(f"Session lost during {attempt.spec.line!r}")
829: +            ),
830:              SessionLossAction.VALIDATE: lambda: self._pending.clear(),
831:          }
832:          action_handlers[action]()
833:  
834: -    def _restart_active_block(self):
835: +    def _restart_active_block(self, attempt, reason):
836: +        retries = self._recovery_retries.get(attempt.block_index, 0)
837: +        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
838: +            self._handle_work_error(RuntimeError(
839: +                f"{reason} repeatedly during {attempt.spec.line!r}; "
840: +                f"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})"
841: +            ))
842: +            return
843: +        self._recovery_retries[attempt.block_index] = retries + 1
844:          self._pending = deque(self._active_commands)
845: -
846: -    @staticmethod
847: -    def _raise_session_loss(attempt):
848: -        raise RuntimeError(f"Session lost during {attempt.spec.line!r}")
849: +        self._replay_context_target = self._block_prompt_context
850: +        self._context_reset_attempted = False
851: +        self.logger.warning(
852: +            "%s during %s/%r; replaying block (command recovery %d/%d)",
853: +            reason, self._active_feature.name, attempt.spec.line,
854: +            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,
855: +        )
856:  
857:      def enqueue_runtime_feature(self, feature):
858:          return self.enqueue_runtime_features([feature])
859:  
860:      def enqueue_runtime_features(self, features):
861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py
862: index 4c2d808..3c112e1 100755
863: --- a/fortinet/common/launch.py
864: +++ b/fortinet/common/launch.py
865: @@ -30,11 +30,11 @@ from .features import (
866:      InstallPkiCertificates,
867:      ApplyStartupConfig,
868:      ValidateProduct,
869:  )
870:  from .env import get_env
871: -from .fos_cli_driver import FOSCliDriver
872: +from .fos_cli_driver import FOSCliDriver, KernelPanicError
873:  from .fos_commander import FOSCommander
874:  from .host_forwarded_bridge import HostForwardedBridge
875:  from .net_mgmt_strategy import NetMgmtStrategy
876:  from .passthrough_redirect import PassthroughRedirect
877:  from .terminal import Terminal
878: @@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):
879:          """
880:          if self._bootstrap_error is not None:
881:              return False
882:          try:
883:              self.driver.process_state()
884: +        except KernelPanicError:
885: +            self.stop()
886: +            raise
887:          except Exception as error:
888:              if self._exit_on_bootstrap_error or self.commander.startup_complete:
889:                  self.stop()
890:                  raise
891:              failed_work = self.commander.continue_after_error(
892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py
893: index 368238c..d124474 100644
894: --- a/fortinet/common/terminal.py
895: +++ b/fortinet/common/terminal.py
896: @@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():
897:  
898:  
899:  class Data:
900:      """A byte view returned by Terminal.expect with authority to discard itself."""
901:  
902: -    def __init__(self, value, discard_callback=None):
903: +    def __init__(self, value, discard_callback=None, *, received_new_data=None):
904:          self.value = bytes(value)
905:          self._discard_callback = discard_callback
906:          self.discarded = False
907: +        self.received_new_data = (
908: +            bool(self.value) if received_new_data is None else received_new_data
909: +        )
910:  
911:      def __bytes__(self):
912:          return self.value
913:  
914:      def __bool__(self):
915: @@ -213,36 +216,46 @@ class Terminal:
916:      def expect(self, regex_list, timeout=None):
917:          """Read until a pattern matches, retaining unmatched data across calls.
918:  
919:          The match ending earliest in the buffered stream wins. Data through that
920:          match is returned and discarded; data after it remains buffered.
921: +        On timeout, the entire unmatched buffer is returned for inspection and
922: +        stays buffered unless the caller explicitly discards it.
923:          """
924:          self._ensure_reader()
925:          deadline = None if timeout is None else time.monotonic() + timeout
926: -        received = bytearray()
927: +        received_new_data = False
928:          result = self._match(regex_list)
929:  
930:          while result is None:
931:              remaining = None if deadline is None else deadline - time.monotonic()
932:              if remaining is not None and remaining <= 0:
933: -                return -1, None, Data(bytes(received), self._discard_prefix)
934: +                return -1, None, Data(
935: +                    self._buffer,
936: +                    self._discard_prefix,
937: +                    received_new_data=received_new_data,
938: +                )
939:  
940:              data = self._read_queue.get(remaining)
941:              if data:
942:                  self._buffer.extend(data)
943:                  self._enforce_buffer_limit()
944: -                received.extend(data)
945: +                received_new_data = True
946:                  if (
947:                      get_env(RAW_SERIAL_LOG_ENV, "").lower() in ("1", "true", "yes")
948:                      and self._output_suppression_depth == 0
949:                  ):
950: -                    self._logger.log(TRACE_LEVEL - 1, f"buffer: {self._buffer}")
951: +                    self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")
952:                  result = self._match(regex_list)
953:                  continue
954:  
955:              if deadline is not None and time.monotonic() >= deadline:
956: -                return -1, None, Data(bytes(received), self._discard_prefix)
957: +                return -1, None, Data(
958: +                    self._buffer,
959: +                    self._discard_prefix,
960: +                    received_new_data=received_new_data,
961: +                )
962:  
963:          index, match = result
964:          consumed = bytes(self._buffer[:match.end()])
965:          stable_match = re.search(regex_list[index], consumed)
966:          del self._buffer[:match.end()]
967: @@ -251,11 +264,14 @@ class Terminal:
968:      def _discard_prefix(self, data):
969:          """Discard bytes that a caller has consumed from the retained buffer."""
970:          if not data:
971:              return
972:          if not self._buffer.startswith(data):
973: -            self._logger.debug("Refusing to discard non-prefix terminal output")
974: +            message = "Refusing to discard non-prefix terminal output"
975: +            if self._logger.isEnabledFor(TRACE_LEVEL):
976: +                message += f": data={data!r}; buffer={self._buffer!r}"
977: +            self._logger.warning(message)
978:              return
979:          del self._buffer[:len(data)]
980:  
981:      def _enforce_buffer_limit(self):
982:          if len(self._buffer) <= self._buffer_limit:
983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md
984: index 1d95aea..37c576e 100644
985: --- a/fortinet/fortigate/README.md
986: +++ b/fortinet/fortigate/README.md
987: @@ -167,11 +167,15 @@ config system global
988:      set alias "lab-fgt"
989:  end
990:  ```
991:  
992:  The importer validates basic `config` / `edit` / `next` / `end` nesting and
993: -fails startup on malformed structure.
994: +fails startup on malformed structure or unterminated quoted strings. Single-
995: +and double-quoted values can span lines. Newlines, whitespace, blank lines,
996: +and scope keywords inside a quoted value are preserved. Each continued line
997: +is sent only after the CLI's continuation prompt; the closing line must return
998: +to a command prompt. An unexpected prompt follows the bootstrap error policy.
999:  
1000:  The bootstrap DNS servers selected from the container resolver or
1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config
1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS
1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup
1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md
1005: index 9e11b86..74a118d 100644
1006: --- a/fortinet/fortigate/docker/README.md
1007: +++ b/fortinet/fortigate/docker/README.md
1008: @@ -35,12 +35,15 @@ Important behavior:
1009:  - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of
1010:    writing to the serial connection directly. The writer preserves write order
1011:    and sends one queued chunk at a time, so commander/driver state handling is
1012:    not paced by each scrapli write call.
1013:  - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte
1014: -  view of what was just read or matched, and timeout `Data` can discard bytes
1015: -  from the terminal's retained buffer.
1016: +  view of the matched prefix or, on timeout, the entire unmatched buffer.
1017: +  Inspecting timeout `Data` leaves those bytes buffered so later input can
1018: +  complete a partial token. Calling `discard()` explicitly consumes the view.
1019: +  `received_new_data` distinguishes fresh input from another inspection of the
1020: +  same retained bytes, so idle waits still advance the driver's stall timer.
1021:  - When multiple regexes match buffered output, the match that ends earliest
1022:    wins. This avoids later, broader prompt patterns swallowing earlier prompts.
1023:  - Matched bytes are consumed from the buffer; bytes after the match stay queued
1024:    for the next state parse.
1025:  - Timeout bytes are not consumed automatically. A command, feature, or commander
1026: @@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.
1027:  The dispatcher sends one command at a time and waits for an appropriate state
1028:  before continuing. By default, a command completes at the next command prompt.
1029:  Some commands override completion states, for example confirmation prompts or
1030:  reboot messages.
1031:  
1032: +Scope-closing commands (`next` and `end`) always capture their output and check
1033: +for `Command fail. Return code <number>`, including builds that append a period
1034: +after the code. A closing failure stops the feature before completion callbacks
1035: +or further commands, even when `fail_on_error=False`. It follows the bootstrap
1036: +error policy: abort normally, or skip the failed feature when
1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for
1038: +individual `set` commands, which can deliberately tolerate unsupported fields.
1039: +
1040:  Session loss is explicit. Each command carries a `SessionLossAction`:
1041:  
1042:  - `RESTART_BLOCK`: replay the current block from the start
1043:  - `COMPLETE_BLOCK`: treat the block as complete
1044:  - `CONTINUE`: do not replay the disruptive command
1045:  - `VALIDATE`: reserve for commands that need post-loss validation
1046: -- `FAIL`: raise immediately
1047: +- `FAIL`: report failure through the configured bootstrap error policy
1048:  
1049:  This matters because commands such as license restore and password updates can
1050:  drop the active admin session. Replaying them blindly can corrupt state or loop.
1051:  
1052: +Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.
1053: +The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,
1054: +commands that allow session-loss replay also allow context-loss replay; commands
1055: +with another session-loss policy decline context-loss replay unless explicitly
1056: +configured otherwise. Context loss does not invoke session-loss callbacks, since
1057: +those may commit credential or licensing transitions.
1058: +
1059: +The commander allows one recovery per command position within a submitted block,
1060: +shared between context loss and session loss. Recovery replays the block's scope
1061: +openers and commands. If necessary, the commander sends one `abort` to restore
1062: +the block's initial prompt context before replay. A repeated loss at the same
1063: +command or failure to restore that context follows the bootstrap error policy.
1064: +The allowance resets when the feature submits a new block. Cleanup commands also
1065: +have one session-loss retry. Attempts expose `retry_count` and the prompt context
1066: +before and after execution so features can make their recovery decision.
1067: +
1068:  The dispatcher also manages cleanup actions and standard-output contexts.
1069:  Features can request console output mode `standard` for machine-readable output;
1070:  the dispatcher detects the current console mode, changes it only when needed,
1071:  and restores `more` after the feature completes.
1072:  
1073: @@ -219,22 +246,23 @@ begin_activation()
1074:  on_command_dispatched(attempt)
1075:  on_output(output)
1076:  on_command_executed(command, state)
1077:  on_block_complete()
1078:  on_session_loss(attempt)
1079: +on_context_loss(attempt)
1080:  mark_completed()
1081:  ```
1082:  
1083:  Static command features subclass `StaticFeature`; they submit a fixed list of
1084:  blocks and complete after the last block. Dynamic features subclass `Feature`
1085:  and submit follow-up blocks based on command output or timer ticks.
1086:  
1087:  Current bootstrap stages are:
1088:  
1089:  - `disk-format`: formats additional disks after the first FortiGate log disk
1090: -- `admin`: disables password policy, creates/updates the desired admin, and
1091: -  handles session loss during password changes
1092: +- `admin`: disables password policy, creates/updates the desired admin, then
1093: +  logs out and waits for console authentication before later stages run
1094:  - `image-info`: reads `get system status` once and stores the parsed
1095:    platform, major, minor, patch, and build on `vm.fos_version` for later
1096:    features
1097:  - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against
1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint
1099: @@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept
1100:  a blank default password first. The driver keeps separate bootstrap and desired
1101:  credentials so it can answer prompts with the password that is valid at that
1102:  moment.
1103:  
1104:  The desired credentials are activated after the admin edit commits. Password
1105: -command output is checked for FortiOS command failures. After a password
1106: -change, the driver first tries the desired credentials. If FortiOS rejects
1107: +command output is checked for FortiOS command failures. After closing the admin
1108: +configuration, the feature sends `exit` and waits for a successful login and CLI
1109: +prompt before completing. A logout during the commit also activates the new
1110: +credentials without replaying the password change. The driver first tries the
1111: +desired credentials. If FortiOS rejects
1112:  them, it retries immediately with the previously accepted credentials, without
1113:  replacing the desired credentials used for later logins.
1114:  
1115:  ### Prompt patterns change during bootstrap
1116:  
1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py
1118: new file mode 100644
1119: index 0000000..7dc469b
1120: --- /dev/null
1121: +++ b/fortinet/tests/test_common_admin_credentials.py
1122: @@ -0,0 +1,154 @@
1123: +"""Admin credential commits followed by logout and console authentication."""
1124: +
1125: +import sys
1126: +import unittest
1127: +from pathlib import Path
1128: +from types import SimpleNamespace
1129: +from unittest.mock import MagicMock, patch
1130: +
1131: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1132: +
1133: +from fortinet.common.common import Credentials
1134: +from fortinet.common.features.credentials import CredentialsFeature
1135: +from fortinet.common.fos_cli_driver import FOSCliDriver
1136: +from fortinet.common.fos_commander import FOSCommander
1137: +from fortinet.common.terminal import Terminal
1138: +from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection
1139: +
1140: +
1141: +LOGIN = b"fw login:\r\n"
1142: +READY = b"Welcome!\r\nfw #\r\n"
1143: +ADMIN_PROMPT = b"fw (admin) #\r\n"
1144: +
1145: +
1146: +class AdminCredentialsTests(unittest.TestCase):
1147: +    def make_stack(self, *, password="newpass", username="admin",
1148: +                   auto_logout=None, authenticate=True, reject=False,
1149: +                   exit_works=True):
1150: +        logger = MagicMock()
1151: +        policy_prompt = b"fw (password-policy) #\r\n"
1152: +        old_password_responses = [READY]
1153: +        if password:
1154: +            old_password_responses.append(ADMIN_PROMPT)
1155: +        old_password_responses.append(b"Login incorrect\r\n" + LOGIN)
1156: +        end_count = 0
1157: +
1158: +        def end_response():
1159: +            nonlocal end_count
1160: +            end_count += 1
1161: +            return LOGIN if auto_logout == "end" and end_count == 2 else b"fw #\r\n"
1162: +
1163: +        login_reply = None if not authenticate else (
1164: +            b"Login incorrect\r\n" + LOGIN if reject else READY
1165: +        )
1166: +        responses = {
1167: +            b"admin\r": b"Password:",
1168: +            b"oldpass\r": lambda: old_password_responses.pop(0),
1169: +            b"config system password-policy\r": policy_prompt,
1170: +            b"set status disable\r": policy_prompt,
1171: +            b"config system admin\r": ADMIN_PROMPT,
1172: +            f"edit {username}\r".encode(): ADMIN_PROMPT,
1173: +            b"set accprofile super_admin\r": ADMIN_PROMPT,
1174: +            b"next\r": LOGIN if auto_logout == "next" else ADMIN_PROMPT,
1175: +            b"end\r": end_response,
1176: +            b"exit\r": LOGIN if exit_works else b"fw #\r\n",
1177: +            b"probe\r": b"fw #\r\n",
1178: +            (password + "\r").encode(): login_reply,
1179: +        }
1180: +        if username != "admin":
1181: +            responses[(username + "\r").encode()] = b"Password:"
1182: +        if password:
1183: +            responses[f"set password {password}\r".encode()] = (
1184: +                b"Please enter current administrator password: "
1185: +            )
1186: +        else:
1187: +            responses[b"unset password\r"] = ADMIN_PROMPT
1188: +
1189: +        connection = SerialConnection(responses)
1190: +        terminal = Terminal(connection, logger)
1191: +        commander = FOSCommander(terminal, logger)
1192: +        credentials = Credentials("admin", "oldpass")
1193: +        driver = FOSCliDriver(
1194: +            terminal, commander, credentials, logger, "bootstrap",
1195: +            MagicMock(), MagicMock(), allow_credential_recovery=True,
1196: +        )
1197: +

(Output capped at 50 KB. Showing lines 1-1197. Use offset=1198 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d4b95c001aNrDjSxvU1SpQ2",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d456a5001o3bO2lt54vLSLy",
  "callID": "call_2b11f877ad7346adbf82b6d0",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 1250,
      "offset": 1
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\n2: index ea16d0f..1af3f4d 100644\n3: --- a/fortinet/common/cli_commands.py\n4: +++ b/fortinet/common/cli_commands.py\n5: @@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n6:      CONTINUE = auto()\n7:      VALIDATE = auto()\n8:      FAIL = auto()\n9:  \n10:  \n11: +class ContextLossAction(Enum):\n12: +    RESTART_BLOCK = auto()\n13: +    FAIL = auto()\n14: +\n15: +\n16:  @dataclass(frozen=True, init=False)\n17:  class CommandSpec:\n18:      line: str\n19:      completion_states: tuple = ()\n20:      capture_output: bool = False\n21:      suppress_output: bool = False\n22:      session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n23:      expected_completion_state: object = None\n24:      fail_on_error: bool = False\n25: +    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n26: +    continuation: bool = False\n27:  \n28:      def __init__(self, line, completion_states=(), capture_output=False,\n29:                   suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n30: -                 expected_completion_state=None, fail_on_error=False):\n31: +                 expected_completion_state=None, fail_on_error=False,\n32: +                 context_loss=None, continuation=False):\n33:          object.__setattr__(self, \"line\", line)\n34:          object.__setattr__(self, \"completion_states\", completion_states)\n35:          object.__setattr__(self, \"capture_output\", capture_output)\n36:          object.__setattr__(self, \"suppress_output\", suppress_output)\n37:          object.__setattr__(self, \"session_loss\", session_loss)\n38:          object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n39:          object.__setattr__(self, \"fail_on_error\", fail_on_error)\n40: +        object.__setattr__(self, \"continuation\", continuation)\n41: +        if context_loss is None:\n42: +            # Commands that must not replay after logout must not replay after\n43: +            # an unexpected scope exit either. Features can override this policy.\n44: +            context_loss = (\n45: +                ContextLossAction.RESTART_BLOCK\n46: +                if session_loss == SessionLossAction.RESTART_BLOCK\n47: +                else ContextLossAction.FAIL\n48: +            )\n49: +        object.__setattr__(self, \"context_loss\", context_loss)\n50:          self.__post_init__()\n51:  \n52:      def __post_init__(self):\n53:          if \"\\r\" in self.line or \"\\n\" in self.line:\n54:              raise ValueError(\"CLI commands must contain exactly one line\")\n55:  \n56: +    @property\n57: +    def closes_scope(self):\n58: +        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n59: +\n60:  \n61:  @dataclass\n62:  class CommandAttempt:\n63:      spec: CommandSpec\n64:      number: int\n65:      session_epoch: int\n66:      output: bytearray = field(default_factory=bytearray)\n67: +    prompt_context_before: tuple | None = None\n68: +    prompt_context_after: tuple | None = None\n69: +    block_index: int | None = None\n70: +    retry_count: int = 0\n71:  \n72:      def on_output(self, output):\n73: -        if not self.spec.capture_output:\n74: +        if not (self.spec.capture_output or self.spec.closes_scope):\n75:              return False\n76:          data = bytes(output)\n77:          self.output.extend(data)\n78:          output.discard(data)\n79:          return True\n80: @@ -69,11 +95,11 @@ class Scope:\n81:      @property\n82:      def close_line(self):\n83:          raise NotImplementedError\n84:  \n85:      def flatten(self):\n86: -        commands = [CommandSpec(self.open_line)]\n87: +        commands = flatten_commands(self.open_line)\n88:          for child in self.children:\n89:              commands.extend(flatten_commands(child))\n90:          commands.append(CommandSpec(self.close_line))\n91:          return commands\n92:  \n93: @@ -107,49 +133,43 @@ class SetValue:\n94:          self.fail_on_error = fail_on_error\n95:          self.validate_prompt = validate_prompt\n96:  \n97:      def flatten(self):\n98:          lines = str(self.value).strip().splitlines() or [\"\"]\n99: -        if len(lines) == 1:\n100: -            return [CommandSpec(\n101: -                f'set {self.field} \"{lines[0]}\"',\n102: -                capture_output=True,\n103: -                expected_completion_state=(\n104: -                    FOSCliState.CMD_PROMPT if self.validate_prompt else None\n105: -                ),\n106: -                fail_on_error=self.fail_on_error,\n107: -            )]\n108: -\n109: -        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n110: -        commands = [CommandSpec(\n111: -            f'set {self.field} \"{lines[0]}',\n112: -            completion_states=both_prompts,\n113: -            capture_output=True,\n114: -            expected_completion_state=(\n115: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n116: -            ),\n117: -            fail_on_error=self.fail_on_error,\n118: -        )]\n119: -        commands.extend(CommandSpec(\n120: -            line,\n121: -            completion_states=both_prompts,\n122: -            capture_output=True,\n123: -            expected_completion_state=(\n124: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n125: -            ),\n126: -            fail_on_error=self.fail_on_error,\n127: -        ) for line in lines[1:-1])\n128: +        lines[0] = f'set {self.field} \"{lines[0]}'\n129: +        lines[-1] += '\"'\n130: +        return _flatten_quoted_lines(\n131: +            lines, fail_on_error=self.fail_on_error,\n132: +            validate_prompt=self.validate_prompt,\n133: +        )\n134: +\n135: +\n136: +def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n137: +    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n138: +    commands = []\n139: +    for index, line in enumerate(lines):\n140: +        last_line = index == len(lines) - 1\n141: +        expected = (\n142: +            FOSCliState.CMD_PROMPT if last_line\n143: +            else FOSCliState.MULTILINE_PROMPT\n144: +        )\n145: +        completion_states = ()\n146: +        if len(lines) > 1:\n147: +            completion_states = (\n148: +                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n149: +                if last_line else\n150: +                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n151: +            )\n152:          commands.append(CommandSpec(\n153: -            f'{lines[-1]}\"',\n154: -            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),\n155: +            line,\n156: +            completion_states=completion_states,\n157:              capture_output=True,\n158: -            expected_completion_state=(\n159: -                FOSCliState.CMD_PROMPT if self.validate_prompt else None\n160: -            ),\n161: -            fail_on_error=self.fail_on_error,\n162: +            expected_completion_state=expected if validate_prompt else None,\n163: +            fail_on_error=fail_on_error,\n164: +            continuation=index > 0,\n165:          ))\n166: -        return commands\n167: +    return commands\n168:  \n169:  \n170:  class CommandSequence:\n171:      \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n172:  \n173: @@ -165,10 +185,12 @@ class CommandSequence:\n174:  \n175:  \n176:  def flatten_commands(value):\n177:      \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n178:      if isinstance(value, str):\n179: +        if \"\\n\" in value:\n180: +            return _flatten_quoted_lines(value.split(\"\\n\"))\n181:          return [CommandSpec(value)]\n182:      if isinstance(value, CommandSpec):\n183:          return [value]\n184:      if isinstance(value, (Scope, CommandSequence, SetValue)):\n185:          return value.flatten()\n186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py\n187: index 4ffb817..b020deb 100644\n188: --- a/fortinet/common/common.py\n189: +++ b/fortinet/common/common.py\n190: @@ -21,10 +21,11 @@ class FOSCliState(IntEnum):\n191:      CURRENT_PASSWORD = auto()\n192:      CONFIRMATION = auto()\n193:      CHANGE_PASSWORD_CONFIRM = auto()\n194:      MORE_PROMPT = auto()\n195:      MULTILINE_PROMPT = auto()\n196: +    KERNEL_PANIC = auto()\n197:      UNKNOWN = auto()  # Non-patterns from here on.\n198:      TN_TIMEOUT = auto()\n199:  \n200:  \n201:  GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n203:  )\n204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n209: +    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n210: +    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n211: +)\n212:  \n213:  DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n214:  DEFAULT_USERNAME = \"admin\"\n215:  DEFAULT_PASSWORD = DEFAULT_USERNAME\n216:  \n217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\n218: index 83ebc9b..5dd906a 100644\n219: --- a/fortinet/common/features/base.py\n220: +++ b/fortinet/common/features/base.py\n221: @@ -53,10 +53,14 @@ class Feature:\n222:          self.commander.feature_complete(self)\n223:  \n224:      def on_session_loss(self, attempt):\n225:          return attempt.spec.session_loss\n226:  \n227: +    def on_context_loss(self, attempt):\n228: +        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n229: +        return attempt.spec.context_loss\n230: +\n231:      def reversal_blocks(self):\n232:          \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n233:          return []\n234:  \n235:      def undo(self):\n236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\n237: index b8bc7de..af39225 100644\n238: --- a/fortinet/common/features/credentials.py\n239: +++ b/fortinet/common/features/credentials.py\n240: @@ -1,14 +1,15 @@\n241:  \"\"\"Administrator bootstrap feature.\"\"\"\n242:  \n243: -from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n244: +from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n245: +from ..common import FOSCliState\n246:  \n247:  from .base import StaticFeature\n248:  \n249:  \n250:  class CredentialsFeature(StaticFeature):\n251: -    \"\"\"Configure the administrator and change credentials after password loss.\"\"\"\n252: +    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n253:  \n254:      def __init__(self, vm, commander):\n255:          self._activate_after_admin_commit = False\n256:          self._desired_credentials_activated = False\n257:          self._password_change_committed = False\n258: @@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):\n259:                  fail_on_error=True,\n260:              ))\n261:          super().__init__(vm, commander, \"admin\", [\n262:              ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n263:              ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n264: +            CommandSequence(\"admin-relogin\", [CommandSpec(\n265: +                \"exit\",\n266: +                session_loss=SessionLossAction.CONTINUE,\n267: +                capture_output=True,\n268: +                fail_on_error=True,\n269: +                # A successful logout takes the session-loss path. Returning\n270: +                # straight to a CLI prompt must not count as verification.\n271: +                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n272: +            )]),\n273:          ], on_complete=lambda: self._activate_desired_credentials())\n274:  \n275: +    def on_command_dispatched(self, attempt):\n276: +        if attempt.spec.line == \"exit\":\n277: +            self._activate_desired_credentials()\n278: +        super().on_command_dispatched(attempt)\n279: +\n280:      def on_session_loss(self, attempt):\n281: +        if attempt.spec.line == \"exit\":\n282: +            # The commander resumes this block only at the authenticated CLI\n283: +            # prompt. Clear the logout command so it cannot be replayed.\n284: +            return SessionLossAction.CONTINUE\n285:          if self._is_password_command(attempt.spec.line):\n286:              self._activate_desired_credentials()\n287:              self._activate_after_admin_commit = False\n288:              return SessionLossAction.CONTINUE\n289: +        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n290: +            # Some releases log out during the commit instead of returning\n291: +            # its CLI prompt. Authenticate with the committed password.\n292: +            self._activate_desired_credentials()\n293: +            self._activate_after_admin_commit = False\n294: +            self._password_change_committed = True\n295: +            return SessionLossAction.CONTINUE\n296:          if self._password_change_committed:\n297:              # FortiOS may log out as the admin edit closes. The password\n298:              # command and `next` have already committed the new credentials,\n299:              # so replaying this block would use the previous password again.\n300:              return SessionLossAction.CONTINUE\n301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\n302: index 96a90d3..a5f0de7 100644\n303: --- a/fortinet/common/features/pki.py\n304: +++ b/fortinet/common/features/pki.py\n305: @@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):\n306:      @staticmethod\n307:      def _config_item_block(scope, name, children):\n308:          # A configuration attempt is deliberately best-effort: the feature\n309:          # must be able to inspect the result and fall back to the TFTP import\n310:          # path when a firmware release does not expose this config tree.  If\n311: -        # these wrapper commands keep ``fail_on_error`` enabled, the commander\n312: -        # raises before ``on_command_executed`` can record the failed config\n313: -        # attempt and select the fallback.\n314: +        # opening commands keep ``fail_on_error`` enabled, the commander raises\n315: +        # before ``on_command_executed`` can select that fallback. A return-code\n316: +        # failure from `next` or `end` is always fatal to the feature: the\n317: +        # commander checks scope commits even when fail_on_error is disabled.\n318:          def config_command(line):\n319:              return CommandSpec(line, capture_output=True, fail_on_error=False)\n320:  \n321:          return CommandSequence(f\"{scope}-{name}\", [\n322:              config_command(f\"config {scope}\"),\n323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\n324: index e404fc8..cb99aa4 100644\n325: --- a/fortinet/common/features/startup_config.py\n326: +++ b/fortinet/common/features/startup_config.py\n327: @@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):\n328:              \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n329:          )\n330:      return filtered\n331:  \n332:  \n333: +def _startup_config_commands(config):\n334: +    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n335: +    pending = []\n336: +    quote = None\n337: +    start_line = None\n338: +    for number, raw_line in enumerate(config, start=1):\n339: +        # Text mode normalizes file line endings. Only remove the delimiter;\n340: +        # whitespace and comment/scope-looking lines inside quotes are data.\n341: +        line = raw_line.removesuffix(\"\\n\")\n342: +        if not pending:\n343: +            line = line.lstrip()\n344: +            if not line or line.startswith(\"#\"):\n345: +                continue\n346: +            start_line = number\n347: +\n348: +        escaped = False\n349: +        for character in line:\n350: +            if escaped:\n351: +                escaped = False\n352: +            elif character == \"\\\\\":\n353: +                escaped = True\n354: +            elif character == quote:\n355: +                quote = None\n356: +            elif quote is None and character in {\"'\", '\"'}:\n357: +                quote = character\n358: +\n359: +        if quote is not None or escaped:\n360: +            pending.append(line)\n361: +            continue\n362: +        pending.append(line.rstrip())\n363: +        yield \"\\n\".join(pending)\n364: +        pending.clear()\n365: +\n366: +    if pending:\n367: +        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n368: +        raise ValueError(\n369: +            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n370: +        )\n371: +\n372: +\n373:  def parse_startup_config(path):\n374:      roots = []\n375:      stack = []\n376:      with open(path) as config:\n377: -        for raw_line in config:\n378: -            line = raw_line.strip()\n379: -            if not line or line.startswith(\"#\"):\n380: -                continue\n381: +        for line in _startup_config_commands(config):\n382:              if line.startswith(\"config \"):\n383:                  node = ConfigBlock(line[7:])\n384:                  (stack[-1].children if stack else roots).append(node)\n385:                  stack.append(node)\n386:              elif line.startswith(\"edit \"):\n387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\n388: index fa34100..b527816 100644\n389: --- a/fortinet/common/fos_cli_driver.py\n390: +++ b/fortinet/common/fos_cli_driver.py\n391: @@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10\n392:  EXPECT_TIMEOUT_SECONDS = 1\n393:  UNKNOWN_STALL_SECONDS = 30\n394:  UNKNOWN_STALL_NEWLINE_LIMIT = 3\n395:  \n396:  \n397: +class KernelPanicError(RuntimeError):\n398: +    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n399: +\n400: +\n401:  class FOSCliDriver:\n402:      \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n403:  \n404:      def __init__(\n405:          self,\n406: @@ -65,10 +69,11 @@ class FOSCliDriver:\n407:              FOSCliState.CMD_PROMPT: self._command_prompt,\n408:              FOSCliState.CMD_PROMPT_ECHO: None,\n409:              FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n410:              FOSCliState.LIC_FAIL: self._license_failed,\n411:              FOSCliState.TN_TIMEOUT: self._timeout,\n412: +            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n413:              FOSCliState.UNKNOWN: self._unknown,\n414:          }\n415:  \n416:      @property\n417:      def state_patterns(self):\n418: @@ -145,11 +150,14 @@ class FOSCliDriver:\n419:  \n420:      def _next_state(self):\n421:          index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n422:          if match:\n423:              return FOSCliState(index), output, True\n424: -        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False\n425: +        # A timeout exposes retained bytes too. Only fresh input should reset\n426: +        # the unknown-output stall timer; an unchanged buffer is still idle.\n427: +        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n428: +        return state, output, False\n429:  \n430:      def _handle_state(self, state):\n431:          handler = self._state_handlers.get(state)\n432:          if handler:\n433:              try:\n434: @@ -254,10 +262,14 @@ class FOSCliDriver:\n435:  \n436:      def _unknown(self):\n437:          if self._last_known_state == FOSCliState.REBOOTING:\n438:              self._idle_spins += 1\n439:  \n440: +    @staticmethod\n441: +    def _kernel_panic():\n442: +        raise KernelPanicError(\"Kernel panic detected on serial console\")\n443: +\n444:      def _note_unknown_output(self):\n445:          self._unknown_started_at = time.monotonic()\n446:  \n447:      def _recover_unknown_stall(self):\n448:          if self._unknown_started_at is None:\n449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\n450: index 26312cf..86b1be6 100644\n451: --- a/fortinet/common/fos_commander.py\n452: +++ b/fortinet/common/fos_commander.py\n453: @@ -10,24 +10,29 @@ from .cli_commands import (\n454:      CleanupAction,\n455:      CommandAttempt,\n456:      CommandSequence,\n457:      CommandSpec,\n458:      ConfigBlock,\n459: +    ContextLossAction,\n460:      SessionLossAction,\n461:      flatten_commands,\n462:  )\n463:  from .terminal import Data\n464: -from .common import FOSCliState, TRACE_LEVEL\n465: +from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n466:  \n467:  DISPATCHABLE_COMPLETION_STATES = {\n468:      FOSCliState.CMD_PROMPT,\n469:      FOSCliState.CONFIRMATION,\n470:      FOSCliState.MULTILINE_PROMPT,\n471:  }\n472:  COMMAND_FAILURE_PATTERN = re.compile(\n473:      rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n474:  )\n475: +CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n476: +    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n477: +    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n478: +)\n479:  \n480:  \n481:  @dataclass\n482:  class _StandardOutputContext:\n483:      feature: object\n484: @@ -35,10 +40,11 @@ class _StandardOutputContext:\n485:      phase: str = \"inspect\"\n486:      restore: bool = False\n487:  \n488:  \n489:  class FOSCommander:\n490: +    MAX_COMMAND_RECOVERY_RETRIES = 1\n491:      _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n492:      _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n493:      _CONSOLE_STANDARD_LINE = \"set output standard\"\n494:  \n495:      def __init__(self, terminal, logger, continue_on_error=False):\n496: @@ -65,23 +71,37 @@ class FOSCommander:\n497:          self._start_time = datetime.datetime.now()\n498:          self._continue_on_error = continue_on_error\n499:          self._pending_feature_error = None\n500:          self._current_state = None\n501:          self._callback_failed = False\n502: +        self._prompt_context = None\n503: +        self._block_prompt_context = None\n504: +        self._recovery_retries = {}\n505: +        self._cleanup_retries = {}\n506: +        self._replay_context_target = None\n507: +        self._context_reset_attempted = False\n508: +        self._in_context_reset = False\n509:  \n510:      def _call_feature(self, callback, *args):\n511:          \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n512:          try:\n513:              return callback(*args)\n514:          except Exception as error:\n515: -            if not self._continue_on_error:\n516: -                raise\n517: -            self.logger.exception(\"Bootstrap feature callback failed\")\n518: -            self._pending_feature_error = error\n519: -            self._callback_failed = True\n520: +            self._handle_work_error(error, from_callback=True)\n521:              return None\n522:  \n523: +    def _handle_work_error(self, error, *, from_callback=False):\n524: +        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n525: +        if not self._continue_on_error:\n526: +            raise error\n527: +        if from_callback:\n528: +            self.logger.exception(\"Bootstrap feature callback failed\")\n529: +        else:\n530: +            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n531: +        self._pending_feature_error = error\n532: +        self._callback_failed = True\n533: +\n534:      def _recover_feature_error(self, *, at_idle_prompt=False):\n535:          error = self._pending_feature_error\n536:          if error is None or (\n537:              self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n538:          ):\n539: @@ -143,10 +163,13 @@ class FOSCommander:\n540:              self._inflight = None\n541:              self._suppression.close()\n542:              self._suppression = ExitStack()\n543:  \n544:          self._in_cleanup = False\n545: +        self._replay_context_target = None\n546: +        self._in_context_reset = False\n547: +        self._cleanup_retries.clear()\n548:          self._feature_errors.append((failed_name, str(error)))\n549:          return failed_name\n550:  \n551:      def record_feature_error(self, name, error):\n552:          \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n553: @@ -184,10 +207,14 @@ class FOSCommander:\n554:          if self.busy:\n555:              raise RuntimeError(\"Cannot replace an active command block\")\n556:          commands = tuple(flatten_commands(block))\n557:          self._active_commands = commands\n558:          self._pending = deque(commands)\n559: +        self._block_prompt_context = self._prompt_context\n560: +        self._recovery_retries = {}\n561: +        self._replay_context_target = None\n562: +        self._context_reset_attempted = False\n563:  \n564:      def feature_complete(self, feature):\n565:          if feature is not self._active_feature:\n566:              return\n567:          if self.busy:\n568: @@ -242,10 +269,18 @@ class FOSCommander:\n569:  \n570:      def on_state(self, state, output):\n571:          \"\"\"Called by the driver for every recognized serial state.\"\"\"\n572:          self._current_state = state\n573:          self._callback_failed = False\n574: +        if state == FOSCliState.CMD_PROMPT:\n575: +            context = self._extract_prompt_context(output)\n576: +            if context is not None:\n577: +                self._prompt_context = context\n578: +            # Some releases return directly to a usable prompt after login,\n579: +            # without a Welcome banner. The prompt also ends session recovery.\n580: +            self._authenticated_once = True\n581: +            self._recovering = False\n582:          if self._pending_feature_error is not None:\n583:              if state == FOSCliState.CMD_PROMPT:\n584:                  self._recover_feature_error()\n585:              elif state == FOSCliState.SESSION_LOST:\n586:                  self._session_epoch += 1\n587: @@ -275,13 +310,10 @@ class FOSCommander:\n588:              return\n589:          if state == FOSCliState.CREDENTIAL_ACCEPTED:\n590:              self._authenticated_once = True\n591:              self._recovering = False\n592:              return\n593: -        if state == FOSCliState.CMD_PROMPT:\n594: -            self._authenticated_once = True\n595: -\n596:          if self._inflight and state in (\n597:              self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n598:          ):\n599:              self._complete_inflight(state)\n600:              return\n601: @@ -345,28 +377,41 @@ class FOSCommander:\n602:          self._call_feature(self._active_feature.begin_activation)\n603:          if self._pending_feature_error is None:\n604:              self._call_feature(self._active_feature.activate)\n605:  \n606:      def _dispatch_next(self):\n607: -        if self._inflight or self._recovering:\n608: +        if self._inflight or self._recovering or self._pending_feature_error is not None:\n609: +            return\n610: +        if not self._restore_replay_context():\n611:              return\n612:          if not self._cleanup and self._active_feature is None:\n613:              self._activate_next_feature()\n614:              if self._active_feature is None:\n615:                  return\n616:          if self._cleanup:\n617:              spec = self._cleanup.popleft()\n618:              self._in_cleanup = True\n619: +            block_index = None\n620:          elif not self._pending:\n621:              self._call_feature(self._active_feature.on_block_complete)\n622:              return\n623:          else:\n624:              spec = self._pending.popleft()\n625:              self._in_cleanup = False\n626: +            block_index = len(self._active_commands) - len(self._pending) - 1\n627: +        self._dispatch_command(spec, block_index)\n628: +\n629: +    def _dispatch_command(self, spec, block_index=None):\n630:          self._attempt_number += 1\n631:          self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n632: -        if self._active_feature:\n633: +        self._inflight.prompt_context_before = self._prompt_context\n634: +        self._inflight.block_index = block_index\n635: +        self._inflight.retry_count = (\n636: +            self._cleanup_retries.get(id(spec), 0)\n637: +            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n638: +        )\n639: +        if self._active_feature and not self._in_context_reset:\n640:              self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n641:              if self._pending_feature_error is not None:\n642:                  return\n643:          if spec.suppress_output:\n644:              self._suppression.enter_context(self.terminal.suppress_output())\n645: @@ -380,12 +425,34 @@ class FOSCommander:\n646:      def _complete_inflight(self, state):\n647:          attempt = self._inflight\n648:          self._inflight = None\n649:          self._suppression.close()\n650:          self._suppression = ExitStack()\n651: -        self._validate_completion(attempt, state)\n652: +        attempt.prompt_context_after = self._prompt_context\n653: +        if self._in_context_reset:\n654: +            self._in_context_reset = False\n655: +            self._dispatch_next()\n656: +            return\n657: +        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n658: +            self._handle_context_loss(attempt)\n659: +            if self._pending_feature_error is not None:\n660: +                self._recover_feature_error()\n661: +            else:\n662: +                self._dispatch_next()\n663: +            return\n664: +        try:\n665: +            self._validate_completion(attempt, state)\n666: +        except RuntimeError as error:\n667: +            if state != FOSCliState.CMD_PROMPT:\n668: +                # An interactive prompt cannot safely advance to another feature.\n669: +                raise\n670: +            self._handle_work_error(error)\n671: +            if self._pending_feature_error is not None:\n672: +                self._recover_feature_error()\n673: +            return\n674:          if self._in_cleanup:\n675: +            self._cleanup_retries.pop(id(attempt.spec), None)\n676:              self._in_cleanup = False\n677:              self._dispatch_next()\n678:              return\n679:          if self._is_standard_output_command(attempt.spec):\n680:              self._complete_standard_output_command(attempt)\n681: @@ -404,24 +471,105 @@ class FOSCommander:\n682:          if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n683:              self._dispatch_next()\n684:  \n685:      @staticmethod\n686:      def _validate_completion(attempt, state):\n687: -        if attempt.spec.fail_on_error and (\n688: +        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n689:              failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n690:          ):\n691:              raise RuntimeError(\n692: -                \"FortiOS command failed \"\n693: +                f\"FortiOS command {attempt.spec.line!r} failed \"\n694:                  f\"(return code {failure.group(1).decode()})\"\n695:              )\n696:          expected = attempt.spec.expected_completion_state\n697:          if expected is not None and state != expected:\n698:              raise RuntimeError(\n699:                  \"CLI command completed at unexpected prompt: \"\n700:                  f\"expected {expected.name}, received {state.name}\"\n701:              )\n702:  \n703: +    def _prompt_context_changed(self, attempt):\n704: +        before = attempt.prompt_context_before\n705: +        after = attempt.prompt_context_after\n706: +        return (\n707: +            before is not None\n708: +            and after is not None\n709: +            and before != after\n710: +            and not self._command_may_change_context(attempt.spec)\n711: +        )\n712: +\n713: +    def _handle_context_loss(self, attempt):\n714: +        reason = (\n715: +            \"CLI context changed from \"\n716: +            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n717: +            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n718: +        )\n719: +        if self._in_cleanup:\n720: +            self._handle_work_error(RuntimeError(\n721: +                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n722: +            ))\n723: +            return\n724: +        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n725: +        if self._pending_feature_error is not None:\n726: +            return\n727: +        if action == ContextLossAction.RESTART_BLOCK:\n728: +            self._restart_active_block(attempt, reason)\n729: +        elif action == ContextLossAction.FAIL:\n730: +            self._handle_work_error(RuntimeError(\n731: +                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n732: +            ))\n733: +        else:\n734: +            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n735: +\n736: +    def _restore_replay_context(self):\n737: +        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n738: +        target = self._replay_context_target\n739: +        if target is None:\n740: +            return True\n741: +        if self._prompt_context == target:\n742: +            self._replay_context_target = None\n743: +            return True\n744: +        if self._context_reset_attempted:\n745: +            self._handle_work_error(RuntimeError(\n746: +                \"Unable to restore CLI context before replay: expected \"\n747: +                f\"{self._format_prompt_context(target)}, received \"\n748: +                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n749: +            ))\n750: +            if self._pending_feature_error is not None:\n751: +                self._recover_feature_error()\n752: +            return False\n753: +        self._context_reset_attempted = True\n754: +        self._in_context_reset = True\n755: +        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n756: +        return False\n757: +\n758: +    @staticmethod\n759: +    def _command_may_change_context(spec):\n760: +        if spec.continuation:\n761: +            return False\n762: +        command = spec.line.strip().lower()\n763: +        return (\n764: +            command.startswith((\"config \", \"edit \"))\n765: +            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n766: +            or command == \"set vdom-mode multi-vdom\"\n767: +        )\n768: +\n769: +    @staticmethod\n770: +    def _extract_prompt_context(output):\n771: +        data = bytes(output)\n772: +        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n773: +        if not matches:\n774: +            return None\n775: +        return tuple(\n776: +            item.decode(errors=\"replace\")\n777: +            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n778: +        )\n779: +\n780: +    @staticmethod\n781: +    def _format_prompt_context(context):\n782: +        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n783: +\n784:      def _is_standard_output_command(self, spec):\n785:          context = self._standard_output_context\n786:          return context is not None and (\n787:              spec.line == self._CONSOLE_INSPECT_LINE\n788:              or (context.phase == \"set-standard\" and not self._pending)\n789: @@ -466,11 +614,24 @@ class FOSCommander:\n790:              return\n791:          attempt = self._inflight\n792:          self._inflight = None\n793:          self._suppression.close()\n794:          self._suppression = ExitStack()\n795: +        if self._in_context_reset:\n796: +            # Login may itself restore the target scope. The pending replay\n797: +            # stays bounded by the original command's recovery allowance.\n798: +            self._in_context_reset = False\n799: +            return\n800:          if self._in_cleanup:\n801: +            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n802: +            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n803: +                self._handle_work_error(RuntimeError(\n804: +                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n805: +                    \"retry limit reached\"\n806: +                ))\n807: +                return\n808: +            self._cleanup_retries[id(attempt.spec)] = retries + 1\n809:              self._cleanup.appendleft(attempt.spec)\n810:              self._in_cleanup = False\n811:              return\n812:          self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n813:          action = self._call_feature(\n814: @@ -481,24 +642,39 @@ class FOSCommander:\n815:              return\n816:          self.logger.info(\n817:              f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n818:          )\n819:          action_handlers = {\n820: -            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),\n821: +            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n822: +                attempt, \"session lost\"\n823: +            ),\n824:              SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n825:              SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n826: -            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),\n827: +            SessionLossAction.FAIL: lambda: self._handle_work_error(\n828: +                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n829: +            ),\n830:              SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n831:          }\n832:          action_handlers[action]()\n833:  \n834: -    def _restart_active_block(self):\n835: +    def _restart_active_block(self, attempt, reason):\n836: +        retries = self._recovery_retries.get(attempt.block_index, 0)\n837: +        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n838: +            self._handle_work_error(RuntimeError(\n839: +                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n840: +                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n841: +            ))\n842: +            return\n843: +        self._recovery_retries[attempt.block_index] = retries + 1\n844:          self._pending = deque(self._active_commands)\n845: -\n846: -    @staticmethod\n847: -    def _raise_session_loss(attempt):\n848: -        raise RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n849: +        self._replay_context_target = self._block_prompt_context\n850: +        self._context_reset_attempted = False\n851: +        self.logger.warning(\n852: +            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n853: +            reason, self._active_feature.name, attempt.spec.line,\n854: +            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n855: +        )\n856:  \n857:      def enqueue_runtime_feature(self, feature):\n858:          return self.enqueue_runtime_features([feature])\n859:  \n860:      def enqueue_runtime_features(self, features):\n861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\n862: index 4c2d808..3c112e1 100755\n863: --- a/fortinet/common/launch.py\n864: +++ b/fortinet/common/launch.py\n865: @@ -30,11 +30,11 @@ from .features import (\n866:      InstallPkiCertificates,\n867:      ApplyStartupConfig,\n868:      ValidateProduct,\n869:  )\n870:  from .env import get_env\n871: -from .fos_cli_driver import FOSCliDriver\n872: +from .fos_cli_driver import FOSCliDriver, KernelPanicError\n873:  from .fos_commander import FOSCommander\n874:  from .host_forwarded_bridge import HostForwardedBridge\n875:  from .net_mgmt_strategy import NetMgmtStrategy\n876:  from .passthrough_redirect import PassthroughRedirect\n877:  from .terminal import Terminal\n878: @@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):\n879:          \"\"\"\n880:          if self._bootstrap_error is not None:\n881:              return False\n882:          try:\n883:              self.driver.process_state()\n884: +        except KernelPanicError:\n885: +            self.stop()\n886: +            raise\n887:          except Exception as error:\n888:              if self._exit_on_bootstrap_error or self.commander.startup_complete:\n889:                  self.stop()\n890:                  raise\n891:              failed_work = self.commander.continue_after_error(\n892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\n893: index 368238c..d124474 100644\n894: --- a/fortinet/common/terminal.py\n895: +++ b/fortinet/common/terminal.py\n896: @@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():\n897:  \n898:  \n899:  class Data:\n900:      \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n901:  \n902: -    def __init__(self, value, discard_callback=None):\n903: +    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n904:          self.value = bytes(value)\n905:          self._discard_callback = discard_callback\n906:          self.discarded = False\n907: +        self.received_new_data = (\n908: +            bool(self.value) if received_new_data is None else received_new_data\n909: +        )\n910:  \n911:      def __bytes__(self):\n912:          return self.value\n913:  \n914:      def __bool__(self):\n915: @@ -213,36 +216,46 @@ class Terminal:\n916:      def expect(self, regex_list, timeout=None):\n917:          \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n918:  \n919:          The match ending earliest in the buffered stream wins. Data through that\n920:          match is returned and discarded; data after it remains buffered.\n921: +        On timeout, the entire unmatched buffer is returned for inspection and\n922: +        stays buffered unless the caller explicitly discards it.\n923:          \"\"\"\n924:          self._ensure_reader()\n925:          deadline = None if timeout is None else time.monotonic() + timeout\n926: -        received = bytearray()\n927: +        received_new_data = False\n928:          result = self._match(regex_list)\n929:  \n930:          while result is None:\n931:              remaining = None if deadline is None else deadline - time.monotonic()\n932:              if remaining is not None and remaining <= 0:\n933: -                return -1, None, Data(bytes(received), self._discard_prefix)\n934: +                return -1, None, Data(\n935: +                    self._buffer,\n936: +                    self._discard_prefix,\n937: +                    received_new_data=received_new_data,\n938: +                )\n939:  \n940:              data = self._read_queue.get(remaining)\n941:              if data:\n942:                  self._buffer.extend(data)\n943:                  self._enforce_buffer_limit()\n944: -                received.extend(data)\n945: +                received_new_data = True\n946:                  if (\n947:                      get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n948:                      and self._output_suppression_depth == 0\n949:                  ):\n950: -                    self._logger.log(TRACE_LEVEL - 1, f\"buffer: {self._buffer}\")\n951: +                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n952:                  result = self._match(regex_list)\n953:                  continue\n954:  \n955:              if deadline is not None and time.monotonic() >= deadline:\n956: -                return -1, None, Data(bytes(received), self._discard_prefix)\n957: +                return -1, None, Data(\n958: +                    self._buffer,\n959: +                    self._discard_prefix,\n960: +                    received_new_data=received_new_data,\n961: +                )\n962:  \n963:          index, match = result\n964:          consumed = bytes(self._buffer[:match.end()])\n965:          stable_match = re.search(regex_list[index], consumed)\n966:          del self._buffer[:match.end()]\n967: @@ -251,11 +264,14 @@ class Terminal:\n968:      def _discard_prefix(self, data):\n969:          \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n970:          if not data:\n971:              return\n972:          if not self._buffer.startswith(data):\n973: -            self._logger.debug(\"Refusing to discard non-prefix terminal output\")\n974: +            message = \"Refusing to discard non-prefix terminal output\"\n975: +            if self._logger.isEnabledFor(TRACE_LEVEL):\n976: +                message += f\": data={data!r}; buffer={self._buffer!r}\"\n977: +            self._logger.warning(message)\n978:              return\n979:          del self._buffer[:len(data)]\n980:  \n981:      def _enforce_buffer_limit(self):\n982:          if len(self._buffer) <= self._buffer_limit:\n983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\n984: index 1d95aea..37c576e 100644\n985: --- a/fortinet/fortigate/README.md\n986: +++ b/fortinet/fortigate/README.md\n987: @@ -167,11 +167,15 @@ config system global\n988:      set alias \"lab-fgt\"\n989:  end\n990:  ```\n991:  \n992:  The importer validates basic `config` / `edit` / `next` / `end` nesting and\n993: -fails startup on malformed structure.\n994: +fails startup on malformed structure or unterminated quoted strings. Single-\n995: +and double-quoted values can span lines. Newlines, whitespace, blank lines,\n996: +and scope keywords inside a quoted value are preserved. Each continued line\n997: +is sent only after the CLI's continuation prompt; the closing line must return\n998: +to a command prompt. An unexpected prompt follows the bootstrap error policy.\n999:  \n1000:  The bootstrap DNS servers selected from the container resolver or\n1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\n1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\n1005: index 9e11b86..74a118d 100644\n1006: --- a/fortinet/fortigate/docker/README.md\n1007: +++ b/fortinet/fortigate/docker/README.md\n1008: @@ -35,12 +35,15 @@ Important behavior:\n1009:  - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n1010:    writing to the serial connection directly. The writer preserves write order\n1011:    and sends one queued chunk at a time, so commander/driver state handling is\n1012:    not paced by each scrapli write call.\n1013:  - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n1014: -  view of what was just read or matched, and timeout `Data` can discard bytes\n1015: -  from the terminal's retained buffer.\n1016: +  view of the matched prefix or, on timeout, the entire unmatched buffer.\n1017: +  Inspecting timeout `Data` leaves those bytes buffered so later input can\n1018: +  complete a partial token. Calling `discard()` explicitly consumes the view.\n1019: +  `received_new_data` distinguishes fresh input from another inspection of the\n1020: +  same retained bytes, so idle waits still advance the driver's stall timer.\n1021:  - When multiple regexes match buffered output, the match that ends earliest\n1022:    wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n1023:  - Matched bytes are consumed from the buffer; bytes after the match stay queued\n1024:    for the next state parse.\n1025:  - Timeout bytes are not consumed automatically. A command, feature, or commander\n1026: @@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.\n1027:  The dispatcher sends one command at a time and waits for an appropriate state\n1028:  before continuing. By default, a command completes at the next command prompt.\n1029:  Some commands override completion states, for example confirmation prompts or\n1030:  reboot messages.\n1031:  \n1032: +Scope-closing commands (`next` and `end`) always capture their output and check\n1033: +for `Command fail. Return code <number>`, including builds that append a period\n1034: +after the code. A closing failure stops the feature before completion callbacks\n1035: +or further commands, even when `fail_on_error=False`. It follows the bootstrap\n1036: +error policy: abort normally, or skip the failed feature when\n1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n1038: +individual `set` commands, which can deliberately tolerate unsupported fields.\n1039: +\n1040:  Session loss is explicit. Each command carries a `SessionLossAction`:\n1041:  \n1042:  - `RESTART_BLOCK`: replay the current block from the start\n1043:  - `COMPLETE_BLOCK`: treat the block as complete\n1044:  - `CONTINUE`: do not replay the disruptive command\n1045:  - `VALIDATE`: reserve for commands that need post-loss validation\n1046: -- `FAIL`: raise immediately\n1047: +- `FAIL`: report failure through the configured bootstrap error policy\n1048:  \n1049:  This matters because commands such as license restore and password updates can\n1050:  drop the active admin session. Replaying them blindly can corrupt state or loop.\n1051:  \n1052: +Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n1053: +The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n1054: +commands that allow session-loss replay also allow context-loss replay; commands\n1055: +with another session-loss policy decline context-loss replay unless explicitly\n1056: +configured otherwise. Context loss does not invoke session-loss callbacks, since\n1057: +those may commit credential or licensing transitions.\n1058: +\n1059: +The commander allows one recovery per command position within a submitted block,\n1060: +shared between context loss and session loss. Recovery replays the block's scope\n1061: +openers and commands. If necessary, the commander sends one `abort` to restore\n1062: +the block's initial prompt context before replay. A repeated loss at the same\n1063: +command or failure to restore that context follows the bootstrap error policy.\n1064: +The allowance resets when the feature submits a new block. Cleanup commands also\n1065: +have one session-loss retry. Attempts expose `retry_count` and the prompt context\n1066: +before and after execution so features can make their recovery decision.\n1067: +\n1068:  The dispatcher also manages cleanup actions and standard-output contexts.\n1069:  Features can request console output mode `standard` for machine-readable output;\n1070:  the dispatcher detects the current console mode, changes it only when needed,\n1071:  and restores `more` after the feature completes.\n1072:  \n1073: @@ -219,22 +246,23 @@ begin_activation()\n1074:  on_command_dispatched(attempt)\n1075:  on_output(output)\n1076:  on_command_executed(command, state)\n1077:  on_block_complete()\n1078:  on_session_loss(attempt)\n1079: +on_context_loss(attempt)\n1080:  mark_completed()\n1081:  ```\n1082:  \n1083:  Static command features subclass `StaticFeature`; they submit a fixed list of\n1084:  blocks and complete after the last block. Dynamic features subclass `Feature`\n1085:  and submit follow-up blocks based on command output or timer ticks.\n1086:  \n1087:  Current bootstrap stages are:\n1088:  \n1089:  - `disk-format`: formats additional disks after the first FortiGate log disk\n1090: -- `admin`: disables password policy, creates/updates the desired admin, and\n1091: -  handles session loss during password changes\n1092: +- `admin`: disables password policy, creates/updates the desired admin, then\n1093: +  logs out and waits for console authentication before later stages run\n1094:  - `image-info`: reads `get system status` once and stores the parsed\n1095:    platform, major, minor, patch, and build on `vm.fos_version` for later\n1096:    features\n1097:  - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n1099: @@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept\n1100:  a blank default password first. The driver keeps separate bootstrap and desired\n1101:  credentials so it can answer prompts with the password that is valid at that\n1102:  moment.\n1103:  \n1104:  The desired credentials are activated after the admin edit commits. Password\n1105: -command output is checked for FortiOS command failures. After a password\n1106: -change, the driver first tries the desired credentials. If FortiOS rejects\n1107: +command output is checked for FortiOS command failures. After closing the admin\n1108: +configuration, the feature sends `exit` and waits for a successful login and CLI\n1109: +prompt before completing. A logout during the commit also activates the new\n1110: +credentials without replaying the password change. The driver first tries the\n1111: +desired credentials. If FortiOS rejects\n1112:  them, it retries immediately with the previously accepted credentials, without\n1113:  replacing the desired credentials used for later logins.\n1114:  \n1115:  ### Prompt patterns change during bootstrap\n1116:  \n1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\n1118: new file mode 100644\n1119: index 0000000..7dc469b\n1120: --- /dev/null\n1121: +++ b/fortinet/tests/test_common_admin_credentials.py\n1122: @@ -0,0 +1,154 @@\n1123: +\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n1124: +\n1125: +import sys\n1126: +import unittest\n1127: +from pathlib import Path\n1128: +from types import SimpleNamespace\n1129: +from unittest.mock import MagicMock, patch\n1130: +\n1131: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1132: +\n1133: +from fortinet.common.common import Credentials\n1134: +from fortinet.common.features.credentials import CredentialsFeature\n1135: +from fortinet.common.fos_cli_driver import FOSCliDriver\n1136: +from fortinet.common.fos_commander import FOSCommander\n1137: +from fortinet.common.terminal import Terminal\n1138: +from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n1139: +\n1140: +\n1141: +LOGIN = b\"fw login:\\r\\n\"\n1142: +READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n1143: +ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n1144: +\n1145: +\n1146: +class AdminCredentialsTests(unittest.TestCase):\n1147: +    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n1148: +                   auto_logout=None, authenticate=True, reject=False,\n1149: +                   exit_works=True):\n1150: +        logger = MagicMock()\n1151: +        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n1152: +        old_password_responses = [READY]\n1153: +        if password:\n1154: +            old_password_responses.append(ADMIN_PROMPT)\n1155: +        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n1156: +        end_count = 0\n1157: +\n1158: +        def end_response():\n1159: +            nonlocal end_count\n1160: +            end_count += 1\n1161: +            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n1162: +\n1163: +        login_reply = None if not authenticate else (\n1164: +            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n1165: +        )\n1166: +        responses = {\n1167: +            b\"admin\\r\": b\"Password:\",\n1168: +            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n1169: +            b\"config system password-policy\\r\": policy_prompt,\n1170: +            b\"set status disable\\r\": policy_prompt,\n1171: +            b\"config system admin\\r\": ADMIN_PROMPT,\n1172: +            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n1173: +            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n1174: +            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n1175: +            b\"end\\r\": end_response,\n1176: +            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n1177: +            b\"probe\\r\": b\"fw #\\r\\n\",\n1178: +            (password + \"\\r\").encode(): login_reply,\n1179: +        }\n1180: +        if username != \"admin\":\n1181: +            responses[(username + \"\\r\").encode()] = b\"Password:\"\n1182: +        if password:\n1183: +            responses[f\"set password {password}\\r\".encode()] = (\n1184: +                b\"Please enter current administrator password: \"\n1185: +            )\n1186: +        else:\n1187: +            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n1188: +\n1189: +        connection = SerialConnection(responses)\n1190: +        terminal = Terminal(connection, logger)\n1191: +        commander = FOSCommander(terminal, logger)\n1192: +        credentials = Credentials(\"admin\", \"oldpass\")\n1193: +        driver = FOSCliDriver(\n1194: +            terminal, commander, credentials, logger, \"bootstrap\",\n1195: +            MagicMock(), MagicMock(), allow_credential_recovery=True,\n1196: +        )\n1197: +\n\n(Output capped at 50 KB. Showing lines 1-1197. Use offset=1198 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\nindex ea16d0f..1af3f4d 100644\n--- a/fortinet/common/cli_commands.py\n+++ b/fortinet/common/cli_commands.py\n@@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n     CONTINUE = auto()\n     VALIDATE = auto()\n     FAIL = auto()\n \n \n+class ContextLossAction(Enum):\n+    RESTART_BLOCK = auto()\n+    FAIL = auto()\n+\n+\n @dataclass(frozen=True, init=False)\n class CommandSpec:\n     line: str\n     completion_states: tuple = ()\n     capture_output: bool = False",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\nindex ea16d0f..1af3f4d 100644\n--- a/fortinet/common/cli_commands.py\n+++ b/fortinet/common/cli_commands.py\n@@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n     CONTINUE = auto()\n     VALIDATE = auto()\n     FAIL = auto()\n \n \n+class ContextLossAction(Enum):\n+    RESTART_BLOCK = auto()\n+    FAIL = auto()\n+\n+\n @dataclass(frozen=True, init=False)\n class CommandSpec:\n     line: str\n     completion_states: tuple = ()\n     capture_output: bool = False\n     suppress_output: bool = False\n     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n     expected_completion_state: object = None\n     fail_on_error: bool = False\n+    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n+    continuation: bool = False\n \n     def __init__(self, line, completion_states=(), capture_output=False,\n                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n-                 expected_completion_state=None, fail_on_error=False):\n+                 expected_completion_state=None, fail_on_error=False,\n+                 context_loss=None, continuation=False):\n         object.__setattr__(self, \"line\", line)\n         object.__setattr__(self, \"completion_states\", completion_states)\n         object.__setattr__(self, \"capture_output\", capture_output)\n         object.__setattr__(self, \"suppress_output\", suppress_output)\n         object.__setattr__(self, \"session_loss\", session_loss)\n         object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n         object.__setattr__(self, \"fail_on_error\", fail_on_error)\n+        object.__setattr__(self, \"continuation\", continuation)\n+        if context_loss is None:\n+            # Commands that must not replay after logout must not replay after\n+            # an unexpected scope exit either. Features can override this policy.\n+            context_loss = (\n+                ContextLossAction.RESTART_BLOCK\n+                if session_loss == SessionLossAction.RESTART_BLOCK\n+                else ContextLossAction.FAIL\n+            )\n+        object.__setattr__(self, \"context_loss\", context_loss)\n         self.__post_init__()\n \n     def __post_init__(self):\n         if \"\\r\" in self.line or \"\\n\" in self.line:\n             raise ValueError(\"CLI commands must contain exactly one line\")\n \n+    @property\n+    def closes_scope(self):\n+        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n+\n \n @dataclass\n class CommandAttempt:\n     spec: CommandSpec\n     number: int\n     session_epoch: int\n     output: bytearray = field(default_factory=bytearray)\n+    prompt_context_before: tuple | None = None\n+    prompt_context_after: tuple | None = None\n+    block_index: int | None = None\n+    retry_count: int = 0\n \n     def on_output(self, output):\n-        if not self.spec.capture_output:\n+        if not (self.spec.capture_output or self.spec.closes_scope):\n             return False\n         data = bytes(output)\n         self.output.extend(data)\n         output.discard(data)\n         return True\n@@ -69,11 +95,11 @@ class Scope:\n     @property\n     def close_line(self):\n         raise NotImplementedError\n \n     def flatten(self):\n-        commands = [CommandSpec(self.open_line)]\n+        commands = flatten_commands(self.open_line)\n         for child in self.children:\n             commands.extend(flatten_commands(child))\n         commands.append(CommandSpec(self.close_line))\n         return commands\n \n@@ -107,49 +133,43 @@ class SetValue:\n         self.fail_on_error = fail_on_error\n         self.validate_prompt = validate_prompt\n \n     def flatten(self):\n         lines = str(self.value).strip().splitlines() or [\"\"]\n-        if len(lines) == 1:\n-            return [CommandSpec(\n-                f'set {self.field} \"{lines[0]}\"',\n-                capture_output=True,\n-                expected_completion_state=(\n-                    FOSCliState.CMD_PROMPT if self.validate_prompt else None\n-                ),\n-                fail_on_error=self.fail_on_error,\n-            )]\n-\n-        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n-        commands = [CommandSpec(\n-            f'set {self.field} \"{lines[0]}',\n-            completion_states=both_prompts,\n-            capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n-        )]\n-        commands.extend(CommandSpec(\n-            line,\n-            completion_states=both_prompts,\n-            capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n-        ) for line in lines[1:-1])\n+        lines[0] = f'set {self.field} \"{lines[0]}'\n+        lines[-1] += '\"'\n+        return _flatten_quoted_lines(\n+            lines, fail_on_error=self.fail_on_error,\n+            validate_prompt=self.validate_prompt,\n+        )\n+\n+\n+def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n+    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n+    commands = []\n+    for index, line in enumerate(lines):\n+        last_line = index == len(lines) - 1\n+        expected = (\n+            FOSCliState.CMD_PROMPT if last_line\n+            else FOSCliState.MULTILINE_PROMPT\n+        )\n+        completion_states = ()\n+        if len(lines) > 1:\n+            completion_states = (\n+                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n+                if last_line else\n+                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n+            )\n         commands.append(CommandSpec(\n-            f'{lines[-1]}\"',\n-            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),\n+            line,\n+            completion_states=completion_states,\n             capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.CMD_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n+            expected_completion_state=expected if validate_prompt else None,\n+            fail_on_error=fail_on_error,\n+            continuation=index > 0,\n         ))\n-        return commands\n+    return commands\n \n \n class CommandSequence:\n     \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n \n@@ -165,10 +185,12 @@ class CommandSequence:\n \n \n def flatten_commands(value):\n     \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n     if isinstance(value, str):\n+        if \"\\n\" in value:\n+            return _flatten_quoted_lines(value.split(\"\\n\"))\n         return [CommandSpec(value)]\n     if isinstance(value, CommandSpec):\n         return [value]\n     if isinstance(value, (Scope, CommandSequence, SetValue)):\n         return value.flatten()\ndiff --git a/fortinet/common/common.py b/fortinet/common/common.py\nindex 4ffb817..b020deb 100644\n--- a/fortinet/common/common.py\n+++ b/fortinet/common/common.py\n@@ -21,10 +21,11 @@ class FOSCliState(IntEnum):\n     CURRENT_PASSWORD = auto()\n     CONFIRMATION = auto()\n     CHANGE_PASSWORD_CONFIRM = auto()\n     MORE_PROMPT = auto()\n     MULTILINE_PROMPT = auto()\n+    KERNEL_PANIC = auto()\n     UNKNOWN = auto()  # Non-patterns from here on.\n     TN_TIMEOUT = auto()\n \n \n GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n@@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n )\n FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n+FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n+    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n+    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n+)\n \n DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n DEFAULT_USERNAME = \"admin\"\n DEFAULT_PASSWORD = DEFAULT_USERNAME\n \ndiff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\nindex 83ebc9b..5dd906a 100644\n--- a/fortinet/common/features/base.py\n+++ b/fortinet/common/features/base.py\n@@ -53,10 +53,14 @@ class Feature:\n         self.commander.feature_complete(self)\n \n     def on_session_loss(self, attempt):\n         return attempt.spec.session_loss\n \n+    def on_context_loss(self, attempt):\n+        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n+        return attempt.spec.context_loss\n+\n     def reversal_blocks(self):\n         \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n         return []\n \n     def undo(self):\ndiff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\nindex b8bc7de..af39225 100644\n--- a/fortinet/common/features/credentials.py\n+++ b/fortinet/common/features/credentials.py\n@@ -1,14 +1,15 @@\n \"\"\"Administrator bootstrap feature.\"\"\"\n \n-from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n+from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n+from ..common import FOSCliState\n \n from .base import StaticFeature\n \n \n class CredentialsFeature(StaticFeature):\n-    \"\"\"Configure the administrator and change credentials after password loss.\"\"\"\n+    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n \n     def __init__(self, vm, commander):\n         self._activate_after_admin_commit = False\n         self._desired_credentials_activated = False\n         self._password_change_committed = False\n@@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):\n                 fail_on_error=True,\n             ))\n         super().__init__(vm, commander, \"admin\", [\n             ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n             ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n+            CommandSequence(\"admin-relogin\", [CommandSpec(\n+                \"exit\",\n+                session_loss=SessionLossAction.CONTINUE,\n+                capture_output=True,\n+                fail_on_error=True,\n+                # A successful logout takes the session-loss path. Returning\n+                # straight to a CLI prompt must not count as verification.\n+                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n+            )]),\n         ], on_complete=lambda: self._activate_desired_credentials())\n \n+    def on_command_dispatched(self, attempt):\n+        if attempt.spec.line == \"exit\":\n+            self._activate_desired_credentials()\n+        super().on_command_dispatched(attempt)\n+\n     def on_session_loss(self, attempt):\n+        if attempt.spec.line == \"exit\":\n+            # The commander resumes this block only at the authenticated CLI\n+            # prompt. Clear the logout command so it cannot be replayed.\n+            return SessionLossAction.CONTINUE\n         if self._is_password_command(attempt.spec.line):\n             self._activate_desired_credentials()\n             self._activate_after_admin_commit = False\n             return SessionLossAction.CONTINUE\n+        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n+            # Some releases log out during the commit instead of returning\n+            # its CLI prompt. Authenticate with the committed password.\n+            self._activate_desired_credentials()\n+            self._activate_after_admin_commit = False\n+            self._password_change_committed = True\n+            return SessionLossAction.CONTINUE\n         if self._password_change_committed:\n             # FortiOS may log out as the admin edit closes. The password\n             # command and `next` have already committed the new credentials,\n             # so replaying this block would use the previous password again.\n             return SessionLossAction.CONTINUE\ndiff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\nindex 96a90d3..a5f0de7 100644\n--- a/fortinet/common/features/pki.py\n+++ b/fortinet/common/features/pki.py\n@@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):\n     @staticmethod\n     def _config_item_block(scope, name, children):\n         # A configuration attempt is deliberately best-effort: the feature\n         # must be able to inspect the result and fall back to the TFTP import\n         # path when a firmware release does not expose this config tree.  If\n-        # these wrapper commands keep ``fail_on_error`` enabled, the commander\n-        # raises before ``on_command_executed`` can record the failed config\n-        # attempt and select the fallback.\n+        # opening commands keep ``fail_on_error`` enabled, the commander raises\n+        # before ``on_command_executed`` can select that fallback. A return-code\n+        # failure from `next` or `end` is always fatal to the feature: the\n+        # commander checks scope commits even when fail_on_error is disabled.\n         def config_command(line):\n             return CommandSpec(line, capture_output=True, fail_on_error=False)\n \n         return CommandSequence(f\"{scope}-{name}\", [\n             config_command(f\"config {scope}\"),\ndiff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\nindex e404fc8..cb99aa4 100644\n--- a/fortinet/common/features/startup_config.py\n+++ b/fortinet/common/features/startup_config.py\n@@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):\n             \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n         )\n     return filtered\n \n \n+def _startup_config_commands(config):\n+    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n+    pending = []\n+    quote = None\n+    start_line = None\n+    for number, raw_line in enumerate(config, start=1):\n+        # Text mode normalizes file line endings. Only remove the delimiter;\n+        # whitespace and comment/scope-looking lines inside quotes are data.\n+        line = raw_line.removesuffix(\"\\n\")\n+        if not pending:\n+            line = line.lstrip()\n+            if not line or line.startswith(\"#\"):\n+                continue\n+            start_line = number\n+\n+        escaped = False\n+        for character in line:\n+            if escaped:\n+                escaped = False\n+            elif character == \"\\\\\":\n+                escaped = True\n+            elif character == quote:\n+                quote = None\n+            elif quote is None and character in {\"'\", '\"'}:\n+                quote = character\n+\n+        if quote is not None or escaped:\n+            pending.append(line)\n+            continue\n+        pending.append(line.rstrip())\n+        yield \"\\n\".join(pending)\n+        pending.clear()\n+\n+    if pending:\n+        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n+        raise ValueError(\n+            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n+        )\n+\n+\n def parse_startup_config(path):\n     roots = []\n     stack = []\n     with open(path) as config:\n-        for raw_line in config:\n-            line = raw_line.strip()\n-            if not line or line.startswith(\"#\"):\n-                continue\n+        for line in _startup_config_commands(config):\n             if line.startswith(\"config \"):\n                 node = ConfigBlock(line[7:])\n                 (stack[-1].children if stack else roots).append(node)\n                 stack.append(node)\n             elif line.startswith(\"edit \"):\ndiff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\nindex fa34100..b527816 100644\n--- a/fortinet/common/fos_cli_driver.py\n+++ b/fortinet/common/fos_cli_driver.py\n@@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10\n EXPECT_TIMEOUT_SECONDS = 1\n UNKNOWN_STALL_SECONDS = 30\n UNKNOWN_STALL_NEWLINE_LIMIT = 3\n \n \n+class KernelPanicError(RuntimeError):\n+    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n+\n+\n class FOSCliDriver:\n     \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n \n     def __init__(\n         self,\n@@ -65,10 +69,11 @@ class FOSCliDriver:\n             FOSCliState.CMD_PROMPT: self._command_prompt,\n             FOSCliState.CMD_PROMPT_ECHO: None,\n             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n             FOSCliState.LIC_FAIL: self._license_failed,\n             FOSCliState.TN_TIMEOUT: self._timeout,\n+            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n             FOSCliState.UNKNOWN: self._unknown,\n         }\n \n     @property\n     def state_patterns(self):\n@@ -145,11 +150,14 @@ class FOSCliDriver:\n \n     def _next_state(self):\n         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n         if match:\n             return FOSCliState(index), output, True\n-        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False\n+        # A timeout exposes retained bytes too. Only fresh input should reset\n+        # the unknown-output stall timer; an unchanged buffer is still idle.\n+        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n+        return state, output, False\n \n     def _handle_state(self, state):\n         handler = self._state_handlers.get(state)\n         if handler:\n             try:\n@@ -254,10 +262,14 @@ class FOSCliDriver:\n \n     def _unknown(self):\n         if self._last_known_state == FOSCliState.REBOOTING:\n             self._idle_spins += 1\n \n+    @staticmethod\n+    def _kernel_panic():\n+        raise KernelPanicError(\"Kernel panic detected on serial console\")\n+\n     def _note_unknown_output(self):\n         self._unknown_started_at = time.monotonic()\n \n     def _recover_unknown_stall(self):\n         if self._unknown_started_at is None:\ndiff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\nindex 26312cf..86b1be6 100644\n--- a/fortinet/common/fos_commander.py\n+++ b/fortinet/common/fos_commander.py\n@@ -10,24 +10,29 @@ from .cli_commands import (\n     CleanupAction,\n     CommandAttempt,\n     CommandSequence,\n     CommandSpec,\n     ConfigBlock,\n+    ContextLossAction,\n     SessionLossAction,\n     flatten_commands,\n )\n from .terminal import Data\n-from .common import FOSCliState, TRACE_LEVEL\n+from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n \n DISPATCHABLE_COMPLETION_STATES = {\n     FOSCliState.CMD_PROMPT,\n     FOSCliState.CONFIRMATION,\n     FOSCliState.MULTILINE_PROMPT,\n }\n COMMAND_FAILURE_PATTERN = re.compile(\n     rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n )\n+CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n+    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n+    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n+)\n \n \n @dataclass\n class _StandardOutputContext:\n     feature: object\n@@ -35,10 +40,11 @@ class _StandardOutputContext:\n     phase: str = \"inspect\"\n     restore: bool = False\n \n \n class FOSCommander:\n+    MAX_COMMAND_RECOVERY_RETRIES = 1\n     _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n     _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n     _CONSOLE_STANDARD_LINE = \"set output standard\"\n \n     def __init__(self, terminal, logger, continue_on_error=False):\n@@ -65,23 +71,37 @@ class FOSCommander:\n         self._start_time = datetime.datetime.now()\n         self._continue_on_error = continue_on_error\n         self._pending_feature_error = None\n         self._current_state = None\n         self._callback_failed = False\n+        self._prompt_context = None\n+        self._block_prompt_context = None\n+        self._recovery_retries = {}\n+        self._cleanup_retries = {}\n+        self._replay_context_target = None\n+        self._context_reset_attempted = False\n+        self._in_context_reset = False\n \n     def _call_feature(self, callback, *args):\n         \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n         try:\n             return callback(*args)\n         except Exception as error:\n-            if not self._continue_on_error:\n-                raise\n-            self.logger.exception(\"Bootstrap feature callback failed\")\n-            self._pending_feature_error = error\n-            self._callback_failed = True\n+            self._handle_work_error(error, from_callback=True)\n             return None\n \n+    def _handle_work_error(self, error, *, from_callback=False):\n+        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n+        if not self._continue_on_error:\n+            raise error\n+        if from_callback:\n+            self.logger.exception(\"Bootstrap feature callback failed\")\n+        else:\n+            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n+        self._pending_feature_error = error\n+        self._callback_failed = True\n+\n     def _recover_feature_error(self, *, at_idle_prompt=False):\n         error = self._pending_feature_error\n         if error is None or (\n             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n         ):\n@@ -143,10 +163,13 @@ class FOSCommander:\n             self._inflight = None\n             self._suppression.close()\n             self._suppression = ExitStack()\n \n         self._in_cleanup = False\n+        self._replay_context_target = None\n+        self._in_context_reset = False\n+        self._cleanup_retries.clear()\n         self._feature_errors.append((failed_name, str(error)))\n         return failed_name\n \n     def record_feature_error(self, name, error):\n         \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n@@ -184,10 +207,14 @@ class FOSCommander:\n         if self.busy:\n             raise RuntimeError(\"Cannot replace an active command block\")\n         commands = tuple(flatten_commands(block))\n         self._active_commands = commands\n         self._pending = deque(commands)\n+        self._block_prompt_context = self._prompt_context\n+        self._recovery_retries = {}\n+        self._replay_context_target = None\n+        self._context_reset_attempted = False\n \n     def feature_complete(self, feature):\n         if feature is not self._active_feature:\n             return\n         if self.busy:\n@@ -242,10 +269,18 @@ class FOSCommander:\n \n     def on_state(self, state, output):\n         \"\"\"Called by the driver for every recognized serial state.\"\"\"\n         self._current_state = state\n         self._callback_failed = False\n+        if state == FOSCliState.CMD_PROMPT:\n+            context = self._extract_prompt_context(output)\n+            if context is not None:\n+                self._prompt_context = context\n+            # Some releases return directly to a usable prompt after login,\n+            # without a Welcome banner. The prompt also ends session recovery.\n+            self._authenticated_once = True\n+            self._recovering = False\n         if self._pending_feature_error is not None:\n             if state == FOSCliState.CMD_PROMPT:\n                 self._recover_feature_error()\n             elif state == FOSCliState.SESSION_LOST:\n                 self._session_epoch += 1\n@@ -275,13 +310,10 @@ class FOSCommander:\n             return\n         if state == FOSCliState.CREDENTIAL_ACCEPTED:\n             self._authenticated_once = True\n             self._recovering = False\n             return\n-        if state == FOSCliState.CMD_PROMPT:\n-            self._authenticated_once = True\n-\n         if self._inflight and state in (\n             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n         ):\n             self._complete_inflight(state)\n             return\n@@ -345,28 +377,41 @@ class FOSCommander:\n         self._call_feature(self._active_feature.begin_activation)\n         if self._pending_feature_error is None:\n             self._call_feature(self._active_feature.activate)\n \n     def _dispatch_next(self):\n-        if self._inflight or self._recovering:\n+        if self._inflight or self._recovering or self._pending_feature_error is not None:\n+            return\n+        if not self._restore_replay_context():\n             return\n         if not self._cleanup and self._active_feature is None:\n             self._activate_next_feature()\n             if self._active_feature is None:\n                 return\n         if self._cleanup:\n             spec = self._cleanup.popleft()\n             self._in_cleanup = True\n+            block_index = None\n         elif not self._pending:\n             self._call_feature(self._active_feature.on_block_complete)\n             return\n         else:\n             spec = self._pending.popleft()\n             self._in_cleanup = False\n+            block_index = len(self._active_commands) - len(self._pending) - 1\n+        self._dispatch_command(spec, block_index)\n+\n+    def _dispatch_command(self, spec, block_index=None):\n         self._attempt_number += 1\n         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n-        if self._active_feature:\n+        self._inflight.prompt_context_before = self._prompt_context\n+        self._inflight.block_index = block_index\n+        self._inflight.retry_count = (\n+            self._cleanup_retries.get(id(spec), 0)\n+            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n+        )\n+        if self._active_feature and not self._in_context_reset:\n             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n             if self._pending_feature_error is not None:\n                 return\n         if spec.suppress_output:\n             self._suppression.enter_context(self.terminal.suppress_output())\n@@ -380,12 +425,34 @@ class FOSCommander:\n     def _complete_inflight(self, state):\n         attempt = self._inflight\n         self._inflight = None\n         self._suppression.close()\n         self._suppression = ExitStack()\n-        self._validate_completion(attempt, state)\n+        attempt.prompt_context_after = self._prompt_context\n+        if self._in_context_reset:\n+            self._in_context_reset = False\n+            self._dispatch_next()\n+            return\n+        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n+            self._handle_context_loss(attempt)\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            else:\n+                self._dispatch_next()\n+            return\n+        try:\n+            self._validate_completion(attempt, state)\n+        except RuntimeError as error:\n+            if state != FOSCliState.CMD_PROMPT:\n+                # An interactive prompt cannot safely advance to another feature.\n+                raise\n+            self._handle_work_error(error)\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            return\n         if self._in_cleanup:\n+            self._cleanup_retries.pop(id(attempt.spec), None)\n             self._in_cleanup = False\n             self._dispatch_next()\n             return\n         if self._is_standard_output_command(attempt.spec):\n             self._complete_standard_output_command(attempt)\n@@ -404,24 +471,105 @@ class FOSCommander:\n         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n             self._dispatch_next()\n \n     @staticmethod\n     def _validate_completion(attempt, state):\n-        if attempt.spec.fail_on_error and (\n+        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n         ):\n             raise RuntimeError(\n-                \"FortiOS command failed \"\n+                f\"FortiOS command {attempt.spec.line!r} failed \"\n                 f\"(return code {failure.group(1).decode()})\"\n             )\n         expected = attempt.spec.expected_completion_state\n         if expected is not None and state != expected:\n             raise RuntimeError(\n                 \"CLI command completed at unexpected prompt: \"\n                 f\"expected {expected.name}, received {state.name}\"\n             )\n \n+    def _prompt_context_changed(self, attempt):\n+        before = attempt.prompt_context_before\n+        after = attempt.prompt_context_after\n+        return (\n+            before is not None\n+            and after is not None\n+            and before != after\n+            and not self._command_may_change_context(attempt.spec)\n+        )\n+\n+    def _handle_context_loss(self, attempt):\n+        reason = (\n+            \"CLI context changed from \"\n+            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n+            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n+        )\n+        if self._in_cleanup:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n+            ))\n+            return\n+        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n+        if self._pending_feature_error is not None:\n+            return\n+        if action == ContextLossAction.RESTART_BLOCK:\n+            self._restart_active_block(attempt, reason)\n+        elif action == ContextLossAction.FAIL:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n+            ))\n+        else:\n+            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n+\n+    def _restore_replay_context(self):\n+        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n+        target = self._replay_context_target\n+        if target is None:\n+            return True\n+        if self._prompt_context == target:\n+            self._replay_context_target = None\n+            return True\n+        if self._context_reset_attempted:\n+            self._handle_work_error(RuntimeError(\n+                \"Unable to restore CLI context before replay: expected \"\n+                f\"{self._format_prompt_context(target)}, received \"\n+                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n+            ))\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            return False\n+        self._context_reset_attempted = True\n+        self._in_context_reset = True\n+        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n+        return False\n+\n+    @staticmethod\n+    def _command_may_change_context(spec):\n+        if spec.continuation:\n+            return False\n+        command = spec.line.strip().lower()\n+        return (\n+            command.startswith((\"config \", \"edit \"))\n+            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n+            or command == \"set vdom-mode multi-vdom\"\n+        )\n+\n+    @staticmethod\n+    def _extract_prompt_context(output):\n+        data = bytes(output)\n+        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n+        if not matches:\n+            return None\n+        return tuple(\n+            item.decode(errors=\"replace\")\n+            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n+        )\n+\n+    @staticmethod\n+    def _format_prompt_context(context):\n+        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n+\n     def _is_standard_output_command(self, spec):\n         context = self._standard_output_context\n         return context is not None and (\n             spec.line == self._CONSOLE_INSPECT_LINE\n             or (context.phase == \"set-standard\" and not self._pending)\n@@ -466,11 +614,24 @@ class FOSCommander:\n             return\n         attempt = self._inflight\n         self._inflight = None\n         self._suppression.close()\n         self._suppression = ExitStack()\n+        if self._in_context_reset:\n+            # Login may itself restore the target scope. The pending replay\n+            # stays bounded by the original command's recovery allowance.\n+            self._in_context_reset = False\n+            return\n         if self._in_cleanup:\n+            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n+            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n+                self._handle_work_error(RuntimeError(\n+                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n+                    \"retry limit reached\"\n+                ))\n+                return\n+            self._cleanup_retries[id(attempt.spec)] = retries + 1\n             self._cleanup.appendleft(attempt.spec)\n             self._in_cleanup = False\n             return\n         self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n         action = self._call_feature(\n@@ -481,24 +642,39 @@ class FOSCommander:\n             return\n         self.logger.info(\n             f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n         )\n         action_handlers = {\n-            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),\n+            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n+                attempt, \"session lost\"\n+            ),\n             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n             SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n-            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),\n+            SessionLossAction.FAIL: lambda: self._handle_work_error(\n+                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n+            ),\n             SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n         }\n         action_handlers[action]()\n \n-    def _restart_active_block(self):\n+    def _restart_active_block(self, attempt, reason):\n+        retries = self._recovery_retries.get(attempt.block_index, 0)\n+        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n+                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n+            ))\n+            return\n+        self._recovery_retries[attempt.block_index] = retries + 1\n         self._pending = deque(self._active_commands)\n-\n-    @staticmethod\n-    def _raise_session_loss(attempt):\n-        raise RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n+        self._replay_context_target = self._block_prompt_context\n+        self._context_reset_attempted = False\n+        self.logger.warning(\n+            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n+            reason, self._active_feature.name, attempt.spec.line,\n+            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n+        )\n \n     def enqueue_runtime_feature(self, feature):\n         return self.enqueue_runtime_features([feature])\n \n     def enqueue_runtime_features(self, features):\ndiff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\nindex 4c2d808..3c112e1 100755\n--- a/fortinet/common/launch.py\n+++ b/fortinet/common/launch.py\n@@ -30,11 +30,11 @@ from .features import (\n     InstallPkiCertificates,\n     ApplyStartupConfig,\n     ValidateProduct,\n )\n from .env import get_env\n-from .fos_cli_driver import FOSCliDriver\n+from .fos_cli_driver import FOSCliDriver, KernelPanicError\n from .fos_commander import FOSCommander\n from .host_forwarded_bridge import HostForwardedBridge\n from .net_mgmt_strategy import NetMgmtStrategy\n from .passthrough_redirect import PassthroughRedirect\n from .terminal import Terminal\n@@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):\n         \"\"\"\n         if self._bootstrap_error is not None:\n             return False\n         try:\n             self.driver.process_state()\n+        except KernelPanicError:\n+            self.stop()\n+            raise\n         except Exception as error:\n             if self._exit_on_bootstrap_error or self.commander.startup_complete:\n                 self.stop()\n                 raise\n             failed_work = self.commander.continue_after_error(\ndiff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\nindex 368238c..d124474 100644\n--- a/fortinet/common/terminal.py\n+++ b/fortinet/common/terminal.py\n@@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():\n \n \n class Data:\n     \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n \n-    def __init__(self, value, discard_callback=None):\n+    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n         self.value = bytes(value)\n         self._discard_callback = discard_callback\n         self.discarded = False\n+        self.received_new_data = (\n+            bool(self.value) if received_new_data is None else received_new_data\n+        )\n \n     def __bytes__(self):\n         return self.value\n \n     def __bool__(self):\n@@ -213,36 +216,46 @@ class Terminal:\n     def expect(self, regex_list, timeout=None):\n         \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n \n         The match ending earliest in the buffered stream wins. Data through that\n         match is returned and discarded; data after it remains buffered.\n+        On timeout, the entire unmatched buffer is returned for inspection and\n+        stays buffered unless the caller explicitly discards it.\n         \"\"\"\n         self._ensure_reader()\n         deadline = None if timeout is None else time.monotonic() + timeout\n-        received = bytearray()\n+        received_new_data = False\n         result = self._match(regex_list)\n \n         while result is None:\n             remaining = None if deadline is None else deadline - time.monotonic()\n             if remaining is not None and remaining <= 0:\n-                return -1, None, Data(bytes(received), self._discard_prefix)\n+                return -1, None, Data(\n+                    self._buffer,\n+                    self._discard_prefix,\n+                    received_new_data=received_new_data,\n+                )\n \n             data = self._read_queue.get(remaining)\n             if data:\n                 self._buffer.extend(data)\n                 self._enforce_buffer_limit()\n-                received.extend(data)\n+                received_new_data = True\n                 if (\n                     get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n                     and self._output_suppression_depth == 0\n                 ):\n-                    self._logger.log(TRACE_LEVEL - 1, f\"buffer: {self._buffer}\")\n+                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n                 result = self._match(regex_list)\n                 continue\n \n             if deadline is not None and time.monotonic() >= deadline:\n-                return -1, None, Data(bytes(received), self._discard_prefix)\n+                return -1, None, Data(\n+                    self._buffer,\n+                    self._discard_prefix,\n+                    received_new_data=received_new_data,\n+                )\n \n         index, match = result\n         consumed = bytes(self._buffer[:match.end()])\n         stable_match = re.search(regex_list[index], consumed)\n         del self._buffer[:match.end()]\n@@ -251,11 +264,14 @@ class Terminal:\n     def _discard_prefix(self, data):\n         \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n         if not data:\n             return\n         if not self._buffer.startswith(data):\n-            self._logger.debug(\"Refusing to discard non-prefix terminal output\")\n+            message = \"Refusing to discard non-prefix terminal output\"\n+            if self._logger.isEnabledFor(TRACE_LEVEL):\n+                message += f\": data={data!r}; buffer={self._buffer!r}\"\n+            self._logger.warning(message)\n             return\n         del self._buffer[:len(data)]\n \n     def _enforce_buffer_limit(self):\n         if len(self._buffer) <= self._buffer_limit:\ndiff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\nindex 1d95aea..37c576e 100644\n--- a/fortinet/fortigate/README.md\n+++ b/fortinet/fortigate/README.md\n@@ -167,11 +167,15 @@ config system global\n     set alias \"lab-fgt\"\n end\n ```\n \n The importer validates basic `config` / `edit` / `next` / `end` nesting and\n-fails startup on malformed structure.\n+fails startup on malformed structure or unterminated quoted strings. Single-\n+and double-quoted values can span lines. Newlines, whitespace, blank lines,\n+and scope keywords inside a quoted value are preserved. Each continued line\n+is sent only after the CLI's continuation prompt; the closing line must return\n+to a command prompt. An unexpected prompt follows the bootstrap error policy.\n \n The bootstrap DNS servers selected from the container resolver or\n `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\ndiff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\nindex 9e11b86..74a118d 100644\n--- a/fortinet/fortigate/docker/README.md\n+++ b/fortinet/fortigate/docker/README.md\n@@ -35,12 +35,15 @@ Important behavior:\n - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n   writing to the serial connection directly. The writer preserves write order\n   and sends one queued chunk at a time, so commander/driver state handling is\n   not paced by each scrapli write call.\n - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n-  view of what was just read or matched, and timeout `Data` can discard bytes\n-  from the terminal's retained buffer.\n+  view of the matched prefix or, on timeout, the entire unmatched buffer.\n+  Inspecting timeout `Data` leaves those bytes buffered so later input can\n+  complete a partial token. Calling `discard()` explicitly consumes the view.\n+  `received_new_data` distinguishes fresh input from another inspection of the\n+  same retained bytes, so idle waits still advance the driver's stall timer.\n - When multiple regexes match buffered output, the match that ends earliest\n   wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n - Matched bytes are consumed from the buffer; bytes after the match stay queued\n   for the next state parse.\n - Timeout bytes are not consumed automatically. A command, feature, or commander\n@@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.\n The dispatcher sends one command at a time and waits for an appropriate state\n before continuing. By default, a command completes at the next command prompt.\n Some commands override completion states, for example confirmation prompts or\n reboot messages.\n \n+Scope-closing commands (`next` and `end`) always capture their output and check\n+for `Command fail. Return code <number>`, including builds that append a period\n+after the code. A closing failure stops the feature before completion callbacks\n+or further commands, even when `fail_on_error=False`. It follows the bootstrap\n+error policy: abort normally, or skip the failed feature when\n+`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n+individual `set` commands, which can deliberately tolerate unsupported fields.\n+\n Session loss is explicit. Each command carries a `SessionLossAction`:\n \n - `RESTART_BLOCK`: replay the current block from the start\n - `COMPLETE_BLOCK`: treat the block as complete\n - `CONTINUE`: do not replay the disruptive command\n - `VALIDATE`: reserve for commands that need post-loss validation\n-- `FAIL`: raise immediately\n+- `FAIL`: report failure through the configured bootstrap error policy\n \n This matters because commands such as license restore and password updates can\n drop the active admin session. Replaying them blindly can corrupt state or loop.\n \n+Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n+The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n+commands that allow session-loss replay also allow context-loss replay; commands\n+with another session-loss policy decline context-loss replay unless explicitly\n+configured otherwise. Context loss does not invoke session-loss callbacks, since\n+those may commit credential or licensing transitions.\n+\n+The commander allows one recovery per command position within a submitted block,\n+shared between context loss and session loss. Recovery replays the block's scope\n+openers and commands. If necessary, the commander sends one `abort` to restore\n+the block's initial prompt context before replay. A repeated loss at the same\n+command or failure to restore that context follows the bootstrap error policy.\n+The allowance resets when the feature submits a new block. Cleanup commands also\n+have one session-loss retry. Attempts expose `retry_count` and the prompt context\n+before and after execution so features can make their recovery decision.\n+\n The dispatcher also manages cleanup actions and standard-output contexts.\n Features can request console output mode `standard` for machine-readable output;\n the dispatcher detects the current console mode, changes it only when needed,\n and restores `more` after the feature completes.\n \n@@ -219,22 +246,23 @@ begin_activation()\n on_command_dispatched(attempt)\n on_output(output)\n on_command_executed(command, state)\n on_block_complete()\n on_session_loss(attempt)\n+on_context_loss(attempt)\n mark_completed()\n ```\n \n Static command features subclass `StaticFeature`; they submit a fixed list of\n blocks and complete after the last block. Dynamic features subclass `Feature`\n and submit follow-up blocks based on command output or timer ticks.\n \n Current bootstrap stages are:\n \n - `disk-format`: formats additional disks after the first FortiGate log disk\n-- `admin`: disables password policy, creates/updates the desired admin, and\n-  handles session loss during password changes\n+- `admin`: disables password policy, creates/updates the desired admin, then\n+  logs out and waits for console authentication before later stages run\n - `image-info`: reads `get system status` once and stores the parsed\n   platform, major, minor, patch, and build on `vm.fos_version` for later\n   features\n - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n   the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n@@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept\n a blank default password first. The driver keeps separate bootstrap and desired\n credentials so it can answer prompts with the password that is valid at that\n moment.\n \n The desired credentials are activated after the admin edit commits. Password\n-command output is checked for FortiOS command failures. After a password\n-change, the driver first tries the desired credentials. If FortiOS rejects\n+command output is checked for FortiOS command failures. After closing the admin\n+configuration, the feature sends `exit` and waits for a successful login and CLI\n+prompt before completing. A logout during the commit also activates the new\n+credentials without replaying the password change. The driver first tries the\n+desired credentials. If FortiOS rejects\n them, it retries immediately with the previously accepted credentials, without\n replacing the desired credentials used for later logins.\n \n ### Prompt patterns change during bootstrap\n \ndiff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\nnew file mode 100644\nindex 0000000..7dc469b\n--- /dev/null\n+++ b/fortinet/tests/test_common_admin_credentials.py\n@@ -0,0 +1,154 @@\n+\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from types import SimpleNamespace\n+from unittest.mock import MagicMock, patch\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.common import Credentials\n+from fortinet.common.features.credentials import CredentialsFeature\n+from fortinet.common.fos_cli_driver import FOSCliDriver\n+from fortinet.common.fos_commander import FOSCommander\n+from fortinet.common.terminal import Terminal\n+from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n+\n+\n+LOGIN = b\"fw login:\\r\\n\"\n+READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n+ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n+\n+\n+class AdminCredentialsTests(unittest.TestCase):\n+    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n+                   auto_logout=None, authenticate=True, reject=False,\n+                   exit_works=True):\n+        logger = MagicMock()\n+        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n+        old_password_responses = [READY]\n+        if password:\n+            old_password_responses.append(ADMIN_PROMPT)\n+        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n+        end_count = 0\n+\n+        def end_response():\n+            nonlocal end_count\n+            end_count += 1\n+            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n+\n+        login_reply = None if not authenticate else (\n+            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n+        )\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n+            b\"config system password-policy\\r\": policy_prompt,\n+            b\"set status disable\\r\": policy_prompt,\n+            b\"config system admin\\r\": ADMIN_PROMPT,\n+            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n+            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n+            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n+            b\"end\\r\": end_response,\n+            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n+            b\"probe\\r\": b\"fw #\\r\\n\",\n+            (password + \"\\r\").encode(): login_reply,\n+        }\n+        if username != \"admin\":\n+            responses[(username + \"\\r\").encode()] = b\"Password:\"\n+        if password:\n+            responses[f\"set password {password}\\r\".encode()] = (\n+                b\"Please enter current administrator password: \"\n+            )\n+        else:\n+            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n+\n+        connection = SerialConnection(responses)\n+        terminal = Terminal(connection, logger)\n+        commander = FOSCommander(terminal, logger)\n+        credentials = Credentials(\"admin\", \"oldpass\")\n+        driver = FOSCliDriver(\n+            terminal, commander, credentials, logger, \"bootstrap\",\n+            MagicMock(), MagicMock(), allow_credential_recovery=True,\n+        )\n+",
        "lineStart": 1,
        "lineEnd": 1197,
        "totalLines": 1198,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716435297,
      "end": 1793716435307
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d4b96e001BZ1iupU8224HDh",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d456a5001o3bO2lt54vLSLy",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 47588,
    "input": 7536,
    "output": 89,
    "reasoning": 2331,
    "cache": {
      "read": 37632,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d456a5001o3bO2lt54vLSLy",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716410021,
    "completed": 1793716435314
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 47588,
    "input": 7536,
    "output": 89,
    "reasoning": 2331,
    "cache": {
      "read": 37632,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 18
step-start
{
  "type": "step-start",
  "id": "prt_1a1d4c4120015ZIfhZUl5rdNfI",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4b97a001c1OtnUD47PyDot"
}
Reasoning
Read the rest of the diff.
Reading the rest of the diff.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 1198
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1198: +        def activate_desired():
1199: +            driver.remember_current_credentials()
1200: +            credentials.username = username
1201: +            credentials.password = password
1202: +
1203: +        vm = SimpleNamespace(
1204: +            desired_credentials=Credentials(username, password),
1205: +            activate_desired_credentials=activate_desired,
1206: +        )
1207: +        admin = CredentialsFeature(vm, commander)
1208: +        following = RecordingFeature(commander, "following", ["probe"])
1209: +        commander.start([admin, following])
1210: +        self.addCleanup(lambda: terminal.close() if not connection.closed else None)
1211: +        return connection, commander, driver, admin, following
1212: +
1213: +    def run_driver(self, driver):
1214: +        with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
1215: +                patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.15):
1216: +            driver.process_state()
1217: +
1218: +    def test_logout_and_relogin_after_committing_credentials(self):
1219: +        for username, password in (("admin", "newpass"), ("admin", ""),
1220: +                                   ("operator", "newpass")):
1221: +            with self.subTest(username=username, password_set=bool(password)):
1222: +                conn, cmd, driver, admin, following = self.make_stack(
1223: +                    username=username, password=password,
1224: +                )
1225: +                self.run_driver(driver)
1226: +                self.assertTrue(cmd.ready)
1227: +                self.assertTrue(admin.completed)
1228: +                self.assertTrue(following.completed)
1229: +                logout = conn.writes.index(b"exit\r")
1230: +                self.assertEqual(conn.writes[logout - 1], b"end\r")
1231: +                self.assertEqual(conn.writes[logout + 1:], [
1232: +                    (username + "\r").encode(),
1233: +                    (password + "\r").encode(),
1234: +                    b"probe\r",
1235: +                ])
1236: +                self.assertEqual(conn.writes.count(b"exit\r"), 1)
1237: +
1238: +    def test_later_features_wait_for_authentication(self):
1239: +        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)
1240: +        self.run_driver(driver)
1241: +        self.assertIn(b"exit\r", conn.writes)
1242: +        self.assertIn(b"newpass\r", conn.writes)
1243: +        self.assertNotIn(b"probe\r", conn.writes)
1244: +        self.assertFalse(admin.completed)
1245: +        self.assertFalse(following.completed)
1246: +        self.assertFalse(cmd.ready)
1247: +
1248: +    def test_fortios_logout_at_commit_does_not_replay_password_change(self):
1249: +        for commit_command in ("next", "end"):
1250: +            with self.subTest(commit_command=commit_command):
1251: +                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)
1252: +                self.run_driver(driver)
1253: +                self.assertTrue(cmd.ready)
1254: +                self.assertTrue(admin.completed)
1255: +                self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
1256: +                self.assertEqual(conn.writes.count(b"exit\r"), 1)
1257: +                self.assertEqual(conn.writes.count(b"newpass\r"), 2)
1258: +
1259: +    def test_logout_must_return_to_login(self):
1260: +        conn, _, driver, admin, _ = self.make_stack(exit_works=False)
1261: +        with self.assertRaisesRegex(RuntimeError, "expected PROVIDE_USERNAME"):
1262: +            self.run_driver(driver)
1263: +        self.assertFalse(admin.completed)
1264: +        self.assertNotIn(b"probe\r", conn.writes)
1265: +
1266: +    def test_rejected_credentials_do_not_start_later_features(self):
1267: +        conn, _, driver, admin, _ = self.make_stack(reject=True)
1268: +        with self.assertRaisesRegex(RuntimeError, "Credential rejected"):
1269: +            self.run_driver(driver)
1270: +        self.assertFalse(admin.completed)
1271: +        self.assertNotIn(b"probe\r", conn.writes)
1272: +        self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
1273: +
1274: +
1275: +if __name__ == "__main__":
1276: +    unittest.main()
1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py
1278: new file mode 100644
1279: index 0000000..2afb43a
1280: --- /dev/null
1281: +++ b/fortinet/tests/test_common_recovery.py
1282: @@ -0,0 +1,292 @@
1283: +"""Bounded recovery after a scope exit or an interrupted CLI session."""
1284: +
1285: +import sys
1286: +import unittest
1287: +from pathlib import Path
1288: +from unittest.mock import MagicMock
1289: +
1290: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1291: +
1292: +from fortinet.common.cli_commands import (  # noqa: E402
1293: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,
1294: +    EditBlock, SessionLossAction,
1295: +)
1296: +from fortinet.common.common import FOSCliState  # noqa: E402
1297: +from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402
1298: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1299: +from fortinet.common.terminal import Data  # noqa: E402
1300: +
1301: +
1302: +IP_COMMAND = "set ip 10.0.52.4/24"
1303: +ACCESS_COMMAND = "set allowaccess ping https ssh http"
1304: +
1305: +
1306: +class RecordingFeature(Feature):
1307: +    def __init__(self, commander, block, context_action=None):
1308: +        super().__init__(None, commander, "management")
1309: +        self.block = block
1310: +        self.context_action = context_action
1311: +        self.losses = []
1312: +        self.attempts = []
1313: +        self.executed = []
1314: +
1315: +    def activate(self):
1316: +        self.commander.submit_block(self, self.block)
1317: +
1318: +    def on_command_dispatched(self, attempt):
1319: +        super().on_command_dispatched(attempt)
1320: +        self.attempts.append(attempt)
1321: +
1322: +    def on_command_executed(self, attempt, state):
1323: +        self.executed.append(attempt.spec.line)
1324: +
1325: +    def on_context_loss(self, attempt):
1326: +        self.losses.append(attempt)
1327: +        if self.context_action is not None:
1328: +            return self.context_action
1329: +        return super().on_context_loss(attempt)
1330: +
1331: +
1332: +class RecoveryTests(unittest.TestCase):
1333: +    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,
1334: +                       context_action=None, following=False):
1335: +        terminal = MagicMock()
1336: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error)
1337: +        block = ConfigBlock("system interface", [EditBlock("port1", [
1338: +            ip_command, ACCESS_COMMAND,
1339: +        ])])
1340: +        feature = RecordingFeature(commander, block, context_action)
1341: +        features = [feature]
1342: +        if following:
1343: +            features.append(RecordingFeature(
1344: +                commander, CommandSequence("following", ["get system status"])
1345: +            ))
1346: +        commander.start(features)
1347: +        return commander, terminal, feature
1348: +
1349: +    def prompt(self, commander, context=None):
1350: +        scope = f" ({context})" if context else ""
1351: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(
1352: +            f"FGT-VM64-KVM-NSVHDM{scope} (Interim)#".encode()
1353: +        ))
1354: +
1355: +    def enter_interface(self, commander):
1356: +        self.prompt(commander, "interface")
1357: +        self.prompt(commander, "port1")
1358: +
1359: +    def finish_interface(self, commander):
1360: +        self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
1361: +        self.prompt(commander, "port1")  # allowaccess succeeds; dispatch next.
1362: +        self.prompt(commander, "interface")  # next succeeds; dispatch end.
1363: +        self.prompt(commander)  # end succeeds.
1364: +
1365: +    @staticmethod
1366: +    def writes(terminal):
1367: +        return [call.args[0] for call in terminal.write.call_args_list]
1368: +
1369: +    def reconnect(self, commander):
1370: +        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b"Welcome!"))
1371: +        self.prompt(commander)
1372: +
1373: +    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):
1374: +        commander, terminal, feature = self.make_commander()
1375: +        self.prompt(commander)
1376: +        self.enter_interface(commander)
1377: +        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.
1378: +        self.assertEqual(self.writes(terminal), [
1379: +            "config system interface\r", "edit port1\r", IP_COMMAND + "\r",
1380: +            "config system interface\r",
1381: +        ])
1382: +        self.assertNotIn(IP_COMMAND, feature.executed)
1383: +        self.assertEqual(feature.losses[0].prompt_context_before, ("port1", "Interim"))
1384: +        self.assertEqual(feature.losses[0].prompt_context_after, ("Interim",))
1385: +        self.enter_interface(commander)
1386: +        self.finish_interface(commander)
1387: +        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]
1388: +        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])
1389: +        self.assertTrue(feature.completed)
1390: +        self.assertTrue(commander.ready)
1391: +
1392: +    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):
1393: +        for best_effort in (False, True):
1394: +            with self.subTest(best_effort=best_effort):
1395: +                commander, terminal, feature = self.make_commander(
1396: +                    continue_on_error=best_effort, following=True,
1397: +                )
1398: +                self.prompt(commander)
1399: +                self.enter_interface(commander)
1400: +                self.prompt(commander)
1401: +                self.enter_interface(commander)
1402: +                if best_effort:
1403: +                    self.prompt(commander)
1404: +                    self.assertIn("retry limit", commander.feature_errors[0][1])
1405: +                    self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1406: +                else:
1407: +                    with self.assertRaisesRegex(RuntimeError, "retry limit"):
1408: +                        self.prompt(commander)
1409: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
1410: +                self.assertNotIn(ACCESS_COMMAND + "\r", self.writes(terminal))
1411: +                self.assertFalse(feature.completed)
1412: +
1413: +    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):
1414: +        commander, terminal, feature = self.make_commander()
1415: +        self.prompt(commander)
1416: +        self.enter_interface(commander)
1417: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1418: +        self.reconnect(commander)
1419: +        self.enter_interface(commander)
1420: +        with self.assertRaisesRegex(RuntimeError, "retry limit"):
1421: +            self.prompt(commander)
1422: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
1423: +        self.assertEqual(feature.losses[0].retry_count, 1)
1424: +
1425: +    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):
1426: +        commander, terminal, _feature = self.make_commander(
1427: +            continue_on_error=True, following=True,
1428: +        )
1429: +        self.prompt(commander)
1430: +        self.enter_interface(commander)
1431: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1432: +        self.reconnect(commander)
1433: +        self.enter_interface(commander)
1434: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
1435: +        self.assertNotIn("get system status\r", self.writes(terminal))
1436: +        self.reconnect(commander)
1437: +        self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1438: +        self.assertIn("retry limit", commander.feature_errors[0][1])
1439: +
1440: +    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):
1441: +        commander, terminal, _feature = self.make_commander(
1442: +            continue_on_error=True, following=True,
1443: +        )
1444: +        self.prompt(commander)
1445: +        self.enter_interface(commander)
1446: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1447: +        self.prompt(commander)  # Successful login returns a prompt, no Welcome.
1448: +        self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
1449: +        self.enter_interface(commander)
1450: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
1451: +        self.assertNotIn("get system status\r", self.writes(terminal))
1452: +        self.prompt(commander)  # Exhaustion is handled at this usable prompt.
1453: +        self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1454: +        self.assertIn("retry limit", commander.feature_errors[0][1])
1455: +
1456: +    def test_each_command_position_gets_one_recovery(self):
1457: +        commander, terminal, feature = self.make_commander()
1458: +        self.prompt(commander)
1459: +        self.enter_interface(commander)
1460: +        self.prompt(commander)  # First loss: IP command.
1461: +        self.enter_interface(commander)
1462: +        self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
1463: +        self.prompt(commander)  # Second loss: allowaccess command.
1464: +        self.enter_interface(commander)
1465: +        self.finish_interface(commander)
1466: +        self.assertTrue(feature.completed)
1467: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 3)
1468: +        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + "\r"), 2)
1469: +
1470: +    def test_feature_can_decline_replay_without_running_session_loss_callback(self):
1471: +        for explicit_policy in (False, True):
1472: +            with self.subTest(explicit_policy=explicit_policy):
1473: +                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)
1474: +                commander, terminal, feature = self.make_commander(
1475: +                    ip_command=IP_COMMAND if explicit_policy else spec,
1476: +                    context_action=ContextLossAction.FAIL if explicit_policy else None,
1477: +                )
1478: +                feature.on_session_loss = MagicMock()
1479: +                self.prompt(commander)
1480: +                self.enter_interface(commander)
1481: +                with self.assertRaisesRegex(RuntimeError, "feature declined replay"):
1482: +                    self.prompt(commander)
1483: +                feature.on_session_loss.assert_not_called()
1484: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
1485: +
1486: +    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):
1487: +        spec = CommandSpec(
1488: +            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,
1489: +            context_loss=ContextLossAction.RESTART_BLOCK,
1490: +        )
1491: +        commander, _terminal, feature = self.make_commander(ip_command=spec)
1492: +        feature.on_session_loss = MagicMock()
1493: +        self.prompt(commander)
1494: +        self.enter_interface(commander)
1495: +        self.prompt(commander)
1496: +        self.enter_interface(commander)
1497: +        self.finish_interface(commander)
1498: +        self.assertTrue(feature.completed)
1499: +        feature.on_session_loss.assert_not_called()
1500: +
1501: +    def test_partial_scope_is_aborted_once_before_replay(self):
1502: +        commander, terminal, feature = self.make_commander()
1503: +        self.prompt(commander)
1504: +        self.enter_interface(commander)
1505: +        self.prompt(commander, "interface")  # Only the edit context disappeared.
1506: +        self.assertEqual(self.writes(terminal)[-1], "abort\r")
1507: +        self.prompt(commander)
1508: +        self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
1509: +        self.enter_interface(commander)
1510: +        self.finish_interface(commander)
1511: +        self.assertTrue(feature.completed)
1512: +        self.assertNotIn("abort", feature.executed)
1513: +        self.assertNotIn("abort", [item.spec.line for item in feature.attempts])
1514: +
1515: +    def test_failed_context_reset_does_not_loop(self):
1516: +        commander, terminal, _feature = self.make_commander()
1517: +        self.prompt(commander)
1518: +        self.enter_interface(commander)
1519: +        self.prompt(commander, "interface")
1520: +        with self.assertRaisesRegex(RuntimeError, "Unable to restore CLI context"):
1521: +            self.prompt(commander, "interface")
1522: +        self.assertEqual(self.writes(terminal).count("abort\r"), 1)
1523: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
1524: +
1525: +    def test_session_loss_during_context_reset_resumes_after_login(self):
1526: +        commander, terminal, feature = self.make_commander()
1527: +        self.prompt(commander)
1528: +        self.enter_interface(commander)
1529: +        self.prompt(commander, "interface")
1530: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1531: +        self.reconnect(commander)
1532: +        self.enter_interface(commander)
1533: +        self.finish_interface(commander)
1534: +        self.assertTrue(feature.completed)
1535: +        self.assertEqual(self.writes(terminal).count("abort\r"), 1)
1536: +
1537: +    def test_cleanup_session_loss_is_bounded(self):
1538: +        terminal = MagicMock()
1539: +        commander = FOSCommander(terminal, MagicMock())
1540: +        feature = RecordingFeature(commander, CommandSequence("work", ["get status"]))
1541: +        commander.register_cleanup(feature, CleanupAction(
1542: +            "cleanup", CommandSequence("cleanup", ["get cleanup"]),
1543: +        ))
1544: +        commander.start([feature])
1545: +        self.prompt(commander)
1546: +        self.prompt(commander)  # Begin cleanup after the feature completes.
1547: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1548: +        self.reconnect(commander)
1549: +        with self.assertRaisesRegex(RuntimeError, "retry limit"):
1550: +            commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1551: +        self.assertEqual(self.writes(terminal).count("get cleanup\r"), 2)
1552: +
1553: +    def test_newly_submitted_block_resets_retry_allowance(self):
1554: +        terminal = MagicMock()
1555: +        commander = FOSCommander(terminal, MagicMock())
1556: +        feature = StaticFeature(None, commander, "two-blocks", [
1557: +            ConfigBlock("system global", ["set alias first"]),
1558: +            ConfigBlock("system global", ["set alias second"]),
1559: +        ])
1560: +        commander.start([feature])
1561: +        self.prompt(commander)
1562: +        for _index in range(2):
1563: +            self.prompt(commander, "global")
1564: +            self.prompt(commander)  # Lost context: retry this block.
1565: +            self.prompt(commander, "global")
1566: +            self.prompt(commander, "global")
1567: +            self.prompt(commander)  # End this block and start the next one.
1568: +        self.assertTrue(feature.completed)
1569: +        self.assertEqual(self.writes(terminal).count("set alias first\r"), 2)
1570: +        self.assertEqual(self.writes(terminal).count("set alias second\r"), 2)
1571: +
1572: +
1573: +if __name__ == "__main__":
1574: +    unittest.main()
1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py
1576: new file mode 100644
1577: index 0000000..56ce729
1578: --- /dev/null
1579: +++ b/fortinet/tests/test_common_scope_errors.py
1580: @@ -0,0 +1,154 @@
1581: +"""Scope commit failures are mandatory errors, including best-effort commands."""
1582: +
1583: +import sys
1584: +import unittest
1585: +from pathlib import Path
1586: +from unittest.mock import MagicMock
1587: +
1588: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1589: +
1590: +from fortinet.common.cli_commands import (  # noqa: E402
1591: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,
1592: +)
1593: +from fortinet.common.common import FOSCliState  # noqa: E402
1594: +from fortinet.common.features.base import Feature  # noqa: E402
1595: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1596: +from fortinet.common.terminal import Data  # noqa: E402
1597: +
1598: +
1599: +class RecordingFeature(Feature):
1600: +    def __init__(self, commander, name, commands):
1601: +        super().__init__(None, commander, name)
1602: +        self.commands = commands
1603: +        self.executed = []
1604: +
1605: +    def activate(self):
1606: +        self.commander.submit_block(self, CommandSequence(self.name, self.commands))
1607: +
1608: +    def on_command_executed(self, attempt, state):
1609: +        self.executed.append(attempt.spec.line)
1610: +
1611: +
1612: +class ScopeCommitFailureTests(unittest.TestCase):
1613: +    @staticmethod
1614: +    def prompt(commander, context=None, output=b""):
1615: +        scope = f" ({context})" if context else ""
1616: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(
1617: +            output + f"fw{scope} #".encode()
1618: +        ))
1619: +
1620: +    @staticmethod
1621: +    def writes(terminal):
1622: +        return [call.args[0] for call in terminal.write.call_args_list]
1623: +
1624: +    def test_closing_failure_cannot_be_disabled_or_replayed(self):
1625: +        for close in ("next", "end"):
1626: +            for capture in (False, True):
1627: +                for best_effort in (False, True):
1628: +                    with self.subTest(close=close, capture=capture, best_effort=best_effort):
1629: +                        terminal = MagicMock()
1630: +                        commander = FOSCommander(terminal, MagicMock(), best_effort)
1631: +                        feature = RecordingFeature(commander, "commit", [
1632: +                            CommandSpec(close, capture_output=capture, fail_on_error=False),
1633: +                            "set must-not-run 1",
1634: +                        ])
1635: +                        feature.on_context_loss = MagicMock()
1636: +                        following = RecordingFeature(commander, "following", ["get status"])
1637: +                        commander.start([feature, following])
1638: +                        self.prompt(commander, "port1")
1639: +                        # The failure code can span multiple serial reads.
1640: +                        for chunk in (b"Command fa", b"il. Return co", b"de -542.\r\n"):
1641: +                            data = Data(chunk)
1642: +                            commander.on_output(data)
1643: +                            self.assertTrue(data.discarded)
1644: +                        if best_effort:
1645: +                            self.prompt(commander, "interface")
1646: +                            self.assertEqual(self.writes(terminal), [close + "\r", "get status\r"])
1647: +                            self.assertEqual(commander.feature_errors[0][0], "commit")
1648: +                            self.assertIn("return code -542", commander.feature_errors[0][1])
1649: +                        else:
1650: +                            with self.assertRaisesRegex(RuntimeError, "return code -542"):
1651: +                                self.prompt(commander, "interface")
1652: +                            self.assertEqual(self.writes(terminal), [close + "\r"])
1653: +                        feature.on_context_loss.assert_not_called()
1654: +                        self.assertEqual(feature.executed, [])
1655: +                        self.assertFalse(feature.completed)
1656: +
1657: +    def test_closing_failure_with_same_prompt_still_ejects(self):
1658: +        for code in ("0", "7", "-61"):
1659: +            for suffix in ("", "."):
1660: +                with self.subTest(code=code, suffix=suffix):
1661: +                    terminal = MagicMock()
1662: +                    commander = FOSCommander(terminal, MagicMock())
1663: +                    feature = RecordingFeature(commander, "commit", ["next", "end"])
1664: +                    commander.start([feature])
1665: +                    self.prompt(commander, "port1")
1666: +                    with self.assertRaisesRegex(RuntimeError, f"return code {code}"):
1667: +                        self.prompt(
1668: +                            commander, "port1",
1669: +                            f"  Command fail. Return code {code}{suffix}\r\n".encode(),
1670: +                        )
1671: +                    self.assertEqual(self.writes(terminal), ["next\r"])
1672: +
1673: +    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):
1674: +        for capture in (False, True):
1675: +            with self.subTest(capture=capture):
1676: +                terminal = MagicMock()
1677: +                commander = FOSCommander(terminal, MagicMock())
1678: +                feature = RecordingFeature(commander, "configure", [
1679: +                    ConfigBlock("system interface", [EditBlock("port1", [
1680: +                        CommandSpec("set unsupported 1", capture_output=capture),
1681: +                    ])]),
1682: +                ])
1683: +                commander.start([feature])
1684: +                self.prompt(commander)
1685: +                self.prompt(commander, "interface")
1686: +                self.prompt(commander, "port1")
1687: +                self.prompt(commander, "port1", b"Command fail. Return code -61.\r\n")
1688: +                self.assertEqual(self.writes(terminal)[-1], "next\r")
1689: +                self.prompt(commander, "interface")
1690: +                self.prompt(commander)
1691: +                self.assertTrue(feature.completed)
1692: +                self.assertTrue(commander.ready)
1693: +                self.assertEqual(commander.feature_errors, ())
1694: +
1695: +    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):
1696: +        for best_effort in (False, True):
1697: +            with self.subTest(best_effort=best_effort):
1698: +                terminal = MagicMock()
1699: +                commander = FOSCommander(terminal, MagicMock(), best_effort)
1700: +                feature = RecordingFeature(commander, "work", ["get initial"])
1701: +                following = RecordingFeature(commander, "following", ["get status"])
1702: +                commander.register_cleanup(feature, CleanupAction(
1703: +                    "close", CommandSequence("close", ["end"]),
1704: +                ))
1705: +                commander.start([feature, following])
1706: +                self.prompt(commander)
1707: +                self.prompt(commander)
1708: +                self.assertEqual(self.writes(terminal)[-1], "end\r")
1709: +                if best_effort:
1710: +                    self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
1711: +                    self.assertEqual(commander.feature_errors[0][0], "cleanup")
1712: +                    self.assertEqual(self.writes(terminal)[-1], "get status\r")
1713: +                else:
1714: +                    with self.assertRaisesRegex(RuntimeError, "return code -5"):
1715: +                        self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
1716: +                    self.assertNotIn("get status\r", self.writes(terminal))
1717: +
1718: +    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):
1719: +        terminal = MagicMock()
1720: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)
1721: +        feature = RecordingFeature(commander, "commit", [CommandSpec(
1722: +            "end", completion_states=(FOSCliState.CONFIRMATION,),
1723: +            expected_completion_state=FOSCliState.CMD_PROMPT,
1724: +        )])
1725: +        commander.start([feature])
1726: +        self.prompt(commander, "interface")
1727: +        with self.assertRaisesRegex(RuntimeError, "unexpected prompt"):
1728: +            commander.on_state(FOSCliState.CONFIRMATION, Data(b"Do you want to continue?"))
1729: +        self.assertEqual(self.writes(terminal), ["end\r"])
1730: +        self.assertFalse(feature.completed)
1731: +
1732: +
1733: +if __name__ == "__main__":
1734: +    unittest.main()
1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py
1736: index 1e31693..d633771 100644
1737: --- a/fortinet/tests/test_common_stack_boundaries.py
1738: +++ b/fortinet/tests/test_common_stack_boundaries.py
1739: @@ -38,15 +38,15 @@ class BoundaryFeature(Feature):
1740:  
1741:      def on_session_loss(self, attempt):
1742:          return SessionLossAction.CONTINUE
1743:  
1744:  
1745: -def make_stack(spec, response, *, allow_recovery=False):
1746: +def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b"fw #"):
1747:      logger = MagicMock()
1748:      connection = SerialConnection({
1749:          b"admin\r": b"Password:",
1750: -        b"secret\r": b"Welcome!\r\nfw #\r\n",
1751: +        b"secret\r": b"Welcome!\r\n" + initial_prompt + b"\r\n",
1752:          b"probe\r": response,
1753:      })
1754:      terminal = Terminal(connection, logger, default_wait="fw #")
1755:      commander = FOSCommander(terminal, logger)
1756:      feature = BoundaryFeature(commander, spec)
1757: @@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):
1758:      response = (
1759:          (prompt + " probe" + ending + "captured diagnostic" + ending + prompt + ending)
1760:          .encode()
1761:      )
1762:      spec = CommandSpec("probe", capture_output=True)
1763: -    connection, terminal, commander, driver, feature, states = make_stack(spec, response)
1764: +    connection, terminal, commander, driver, feature, states = make_stack(
1765: +        spec, response, initial_prompt=prompt.encode()
1766: +    )
1767:      try:
1768:          with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
1769:                  patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1770:              driver.process_state()
1771:          assert commander.ready
1772: @@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b"", *, recover=False):
1773:          completion = (state,)
1774:      connection, terminal, commander, driver, feature, states = make_stack(
1775:          CommandSpec("probe", completion_states=completion, capture_output=True),
1776:          response,
1777:          allow_recovery=recover,
1778: +        initial_prompt=b"fw (global) #" if state == FOSCliState.CMD_PROMPT_ECHO else b"fw #",
1779:      )
1780:      try:
1781:          with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.03), \
1782:                  patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1783:              driver.process_state()
1784: @@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):
1785:              self.assertFalse(feature.completed)
1786:              self.assertIn(b"garbage", bytes(feature.current_attempt.output))
1787:          finally:
1788:              terminal.close()
1789:  
1790: -    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):
1791: +    def test_idle_read_exposes_retained_prompt_newline(self):
1792:          connection, terminal, commander, driver, feature, states = make_stack(
1793:              CommandSpec("probe", capture_output=True), None
1794:          )
1795:          try:
1796:              with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
1797:                      patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.04):
1798:                  driver.process_state()
1799:              self.assertIn(FOSCliState.TN_TIMEOUT, states)
1800: -            self.assertEqual(bytes(feature.current_attempt.output), b"")
1801: +            # The login response ended with a newline after the matched CLI
1802: +            # prompt. Full-buffer timeout inspection exposes that real byte.
1803: +            self.assertEqual(bytes(feature.current_attempt.output), b"\n")
1804:              self.assertTrue(commander.busy)
1805:          finally:
1806:              terminal.close()
1807:  
1808:      def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):
1809:          command_echo = b"fw (global) # probe\r\n"
1810:          payload = b"config system dns\r\n set primary 1.1.1.1\r\nend\r\nfw (global) #\r\n"
1811:          response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])
1812:          connection, terminal, commander, driver, feature, states = make_stack(
1813: -            CommandSpec("probe", capture_output=True), response
1814: +            CommandSpec("probe", capture_output=True), response,
1815: +            initial_prompt=b"fw (global) #",
1816:          )
1817:          try:
1818:              with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
1819:                      patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1820:                  driver.process_state()
1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py
1822: index 74d6ef7..56346ea 100644
1823: --- a/fortinet/tests/test_common_stack_parsing.py
1824: +++ b/fortinet/tests/test_common_stack_parsing.py
1825: @@ -7,11 +7,13 @@ from pathlib import Path
1826:  from unittest.mock import MagicMock
1827:  
1828:  REPO_ROOT = Path(__file__).resolve().parents[2]
1829:  sys.path.insert(0, str(REPO_ROOT))
1830:  
1831: -from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402
1832: +from fortinet.common.cli_commands import (  # noqa: E402
1833: +    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,
1834: +)
1835:  from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
1836:  from fortinet.common.features.base import Feature  # noqa: E402
1837:  from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
1838:  from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1839:  from fortinet.common.terminal import Terminal  # noqa: E402
1840: @@ -35,10 +37,12 @@ class SerialConnection:
1841:  
1842:      def write(self, data):
1843:          data = bytes(data)
1844:          self.writes.append(data)
1845:          response = self._responses.get(data)
1846: +        if callable(response):
1847: +            response = response()
1848:          if response:
1849:              chunks = response if isinstance(response, (tuple, list)) else (response,)
1850:              for chunk in chunks:
1851:                  if chunk:
1852:                      self._incoming.put(bytes(chunk))
1853: @@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):
1854:          self.assertEqual(bytes(terminal._buffer), b"")
1855:  
1856:      def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):
1857:          responses = {
1858:              b"admin\r": b"Password:",
1859: -            b"secret\r": b"Welcome!\r\nfw #\r\n",
1860: +            b"secret\r": b"Welcome!\r\nfw (global) #\r\n",
1861:              b"get system status\r": (
1862:                  b"fw (global) # get system status\r\n"
1863:                  b"Version: FortiGate-VM64 v7.4.2,build2571\r\n"
1864:                  b"--More--\r\n"
1865:                  b"Serial-Number: FGVMTEST\r\n"
1866: @@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):
1867:          self.assertIn(b"FortiGate-VM64 v7.4.2,build2571", captured)
1868:          self.assertIn(b"Serial-Number: FGVMTEST", captured)
1869:          self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)
1870:          self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)
1871:  
1872: +    def test_aborted_interface_edit_recovers_through_serial_driver(self):
1873: +        ip_responses = iter([
1874: +            b"abort\r\nfw (Interim)#\r\n",
1875: +            b"fw (port1) (Interim)#\r\n",
1876: +        ])
1877: +        responses = {
1878: +            b"admin\r": b"Password:",
1879: +            b"secret\r": b"Welcome!\r\nfw (Interim)#\r\n",
1880: +            b"config system interface\r": b"fw (interface) (Interim)#\r\n",
1881: +            b"edit port1\r": b"fw (port1) (Interim)#\r\n",
1882: +            b"set ip 10.0.52.4/24\r": lambda: next(ip_responses),
1883: +            b"set allowaccess ping https ssh http\r": b"fw (port1) (Interim)#\r\n",
1884: +            b"next\r": b"fw (interface) (Interim)#\r\n",
1885: +            b"end\r": b"fw (Interim)#\r\n",
1886: +        }
1887: +        feature_ref = []
1888: +
1889: +        def configured(commander):
1890: +            feature = RecordingFeature(commander, "management", [
1891: +                ConfigBlock("system interface", [EditBlock("port1", [
1892: +                    "set ip 10.0.52.4/24", "set allowaccess ping https ssh http",
1893: +                ])]),
1894: +            ])
1895: +            feature_ref.append(feature)
1896: +            return [feature]
1897: +
1898: +        connection, terminal, commander, driver = self.make_stack(configured, responses)
1899: +        try:
1900: +            driver.process_state()
1901: +            self.assertTrue(commander.ready)
1902: +            self.assertTrue(feature_ref[0].completed)
1903: +            self.assertEqual(connection.writes, [
1904: +                b"admin\r", b"secret\r",
1905: +                b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
1906: +                b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
1907: +                b"set allowaccess ping https ssh http\r", b"next\r", b"end\r",
1908: +            ])
1909: +        finally:
1910: +            terminal.close()
1911: +
1912: +    def test_failed_next_ejects_before_end_through_serial_driver(self):
1913: +        responses = {
1914: +            b"admin\r": b"Password:",
1915: +            b"secret\r": b"Welcome!\r\nfw #\r\n",
1916: +            b"config system interface\r": b"fw (interface)#\r\n",
1917: +            b"edit port1\r": b"fw (port1)#\r\n",
1918: +            b"set unsupported 1\r": b"Command fail. Return code -61.\r\nfw (port1)#\r\n",
1919: +            b"next\r": (
1920: +                b"Command fa", b"il. Return code -5.\r\nfw (port1)#\r\n",
1921: +            ),
1922: +        }
1923: +        feature_ref = []
1924: +
1925: +        def configured(commander):
1926: +            feature = RecordingFeature(commander, "management", [
1927: +                ConfigBlock("system interface", [EditBlock("port1", ["set unsupported 1"])]),
1928: +            ])
1929: +            feature_ref.append(feature)
1930: +            return [feature]
1931: +
1932: +        connection, terminal, commander, driver = self.make_stack(configured, responses)
1933: +        try:
1934: +            with self.assertRaisesRegex(RuntimeError, "'next'.*return code -5"):
1935: +                driver.process_state()
1936: +            self.assertEqual(connection.writes, [
1937: +                b"admin\r", b"secret\r", b"config system interface\r",
1938: +                b"edit port1\r", b"set unsupported 1\r", b"next\r",
1939: +            ])
1940: +            self.assertFalse(feature_ref[0].completed)
1941: +            self.assertFalse(commander.ready)
1942: +        finally:
1943: +            terminal.close()
1944: +
1945:  
1946:  if __name__ == "__main__":
1947:      unittest.main()
1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py
1949: index 4c0a37b..be7eab4 100644
1950: --- a/fortinet/tests/test_common_terminal_driver.py
1951: +++ b/fortinet/tests/test_common_terminal_driver.py
1952: @@ -9,12 +9,16 @@ from contextlib import contextmanager
1953:  from unittest.mock import MagicMock, patch
1954:  
1955:  REPO_ROOT = __import__("pathlib").Path(__file__).resolve().parents[2]
1956:  sys.path.insert(0, str(REPO_ROOT))
1957:  
1958: -from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
1959: -from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
1960: +from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402
1961: +from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402
1962: +from fortinet.common.fos_cli_driver import (  # noqa: E402
1963: +    FOSCliDriver,
1964: +    KernelPanicError,
1965: +)
1966:  from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402
1967:  
1968:  
1969:  class ByteQueueTests(unittest.TestCase):
1970:      def test_put_get_close_timeout_and_failure(self):
1971: @@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):
1972:          terminal._buffer_limit = 5
1973:          with self.assertRaisesRegex(RuntimeError, "exceeded 5"):
1974:              terminal._enforce_buffer_limit()
1975:          terminal._logger.error.assert_called_once()
1976:  
1977: +    def test_timeout_preserves_partial_token_for_a_later_read(self):
1978: +        terminal = self.terminal_with_data(b"Login incor")
1979: +        pattern = rb"(?m)^Login incorrect\r?$"
1980: +        index, match, output = terminal.expect([pattern], timeout=0.001)
1981: +        self.assertEqual((index, match), (-1, None))
1982: +        self.assertEqual(bytes(output), b"Login incor")
1983: +        # Inspection without discard keeps the partial token, including when
1984: +        # another wait expires without receiving any more bytes.
1985: +        _, _, output = terminal.expect([pattern], timeout=0)
1986: +        self.assertEqual(bytes(output), b"Login incor")
1987: +        terminal._read_queue.put(b"rect\n")
1988: +        index, match, output = terminal.expect([pattern], timeout=0.1)
1989: +        self.assertEqual(index, 0)
1990: +        self.assertEqual(match.group(), b"Login incorrect")
1991: +        self.assertEqual(bytes(output), b"Login incorrect")
1992: +        self.assertEqual(bytes(terminal._buffer), b"\n")
1993: +
1994: +    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):
1995: +        terminal = self.terminal_with_data(b"Verifying pass")
1996: +        _, _, output = terminal.expect([b"fw #"], timeout=0.001)
1997: +        self.assertIsNone(re.search(rb"Verifying password", bytes(output)))
1998: +
1999: +        terminal._read_queue.put(b"word...\n")
2000: +        _, match, output = terminal.expect([b"fw #"], timeout=0.001)
2001: +        self.assertIsNone(match)
2002: +        self.assertIsNotNone(re.search(rb"Verifying password", bytes(output)))
2003: +        self.assertEqual(bytes(terminal._buffer), b"Verifying password...\n")
2004: +        output.discard()
2005: +        self.assertEqual(bytes(terminal._buffer), b"")
2006: +
2007: +    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):
2008: +        prefix = b"\nVerifying password...\n"
2009: +        chunk = b"admin\nadmin\n"
2010: +        terminal = self.terminal_with_data(chunk)
2011: +        terminal._buffer.extend(prefix)
2012: +
2013: +        _, _, output = terminal.expect([b"fw #"], timeout=0.001)
2014: +        self.assertEqual(bytes(output), prefix + chunk)
2015: +        attempt = CommandAttempt(CommandSpec("end"), 1, 0)
2016: +        attempt.on_output(output)
2017: +
2018: +        self.assertEqual(bytes(attempt.output), prefix + chunk)
2019: +        self.assertEqual(bytes(terminal._buffer), b"")
2020: +        terminal._logger.warning.assert_not_called()
2021: +
2022:      def test_suppression_is_nested_and_restores_context(self):
2023:          @contextmanager
2024:          def context():
2025:              events.append("enter")
2026:              try:
2027: @@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):
2028:          with self.assertRaisesRegex(OSError, "serial failed"):
2029:              queue.get(0)
2030:          logger.exception.assert_called_once()
2031:          with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}):
2032:              self.assertEqual(terminal_buffer_limit_bytes(), 32)
2033: -        with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "0"}):
2034: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "64", "FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}, clear=True):
2035: +            self.assertEqual(terminal_buffer_limit_bytes(), 64)
2036: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "0"}, clear=True):
2037:              with self.assertRaises(ValueError):
2038:                  terminal_buffer_limit_bytes()
2039:  
2040: +    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):
2041: +        for env_name in ("FTNT_LOG_RAW_SERIAL", "FOS_LOG_RAW_SERIAL"):
2042: +            with self.subTest(env_name=env_name):
2043: +                terminal = self.terminal_with_data(b"matched")
2044: +                with patch.dict("os.environ", {env_name: "true"}, clear=True):
2045: +                    terminal.expect([b"matched"], timeout=0.1)
2046: +                terminal._logger.log.assert_called_once_with(
2047: +                    TRACE_LEVEL,
2048: +                    "buffer: bytearray(b'matched')",
2049: +                )
2050: +
2051:  
2052:  class DriverTests(unittest.TestCase):
2053:      def make_driver(self, *, allow_recovery=False):
2054:          terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()
2055:          commander.ready = False
2056: @@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):
2057:          self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)
2058:          terminal.expect.return_value = (-1, None, Data(b""))
2059:          self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)
2060:          driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)
2061:  
2062: +    def test_retained_timeout_output_does_not_count_as_fresh_input(self):
2063: +        driver, _, _, logger, *_ = self.make_driver()
2064: +        terminal = Terminal(MagicMock(), logger)
2065: +        terminal._ensure_reader = lambda: None
2066: +        terminal._read_queue.put(b"partial token")
2067: +        driver._terminal = terminal
2068: +
2069: +        with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.001):
2070: +            state, output, matched = driver._next_state()
2071: +            self.assertEqual(state, FOSCliState.UNKNOWN)
2072: +            self.assertEqual(bytes(output), b"partial token")
2073: +            self.assertFalse(matched)
2074: +            state, output, matched = driver._next_state()
2075: +            self.assertEqual(state, FOSCliState.TN_TIMEOUT)
2076: +            self.assertEqual(bytes(output), b"partial token")
2077: +            self.assertFalse(matched)
2078: +
2079: +    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):
2080: +        driver, terminal, commander, *_ = self.make_driver()
2081: +        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]
2082: +        panic = (
2083: +            b"Kernel panic - not syncing: VFS: Unable to mount root fs\r\n"
2084: +            b"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\r\n"
2085: +        )
2086: +
2087: +        self.assertIsNone(
2088: +            re.search(
2089: +                pattern,
2090: +                b"Kernel panic - not syncing: VFS: Unable to mount root fs",
2091: +            )
2092: +        )
2093: +        match = re.search(pattern, panic)
2094: +        self.assertIsNotNone(match)
2095: +        terminal.expect.return_value = (
2096: +            FOSCliState.KERNEL_PANIC.value,
2097: +            match,
2098: +            Data(panic),
2099: +        )
2100: +
2101: +        with self.assertRaisesRegex(KernelPanicError, "Kernel panic detected"):
2102: +            driver.process_state()
2103: +
2104: +        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))
2105: +
2106:  
2107:  if __name__ == "__main__":
2108:      unittest.main()

(End of file - total 2108 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d4c4c7001yv5ri35rbYOTOY",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4b97a001c1OtnUD47PyDot",
  "callID": "call_f36ea3823d7841fe9855667e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 1198
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1198: +        def activate_desired():\n1199: +            driver.remember_current_credentials()\n1200: +            credentials.username = username\n1201: +            credentials.password = password\n1202: +\n1203: +        vm = SimpleNamespace(\n1204: +            desired_credentials=Credentials(username, password),\n1205: +            activate_desired_credentials=activate_desired,\n1206: +        )\n1207: +        admin = CredentialsFeature(vm, commander)\n1208: +        following = RecordingFeature(commander, \"following\", [\"probe\"])\n1209: +        commander.start([admin, following])\n1210: +        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n1211: +        return connection, commander, driver, admin, following\n1212: +\n1213: +    def run_driver(self, driver):\n1214: +        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n1215: +                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n1216: +            driver.process_state()\n1217: +\n1218: +    def test_logout_and_relogin_after_committing_credentials(self):\n1219: +        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n1220: +                                   (\"operator\", \"newpass\")):\n1221: +            with self.subTest(username=username, password_set=bool(password)):\n1222: +                conn, cmd, driver, admin, following = self.make_stack(\n1223: +                    username=username, password=password,\n1224: +                )\n1225: +                self.run_driver(driver)\n1226: +                self.assertTrue(cmd.ready)\n1227: +                self.assertTrue(admin.completed)\n1228: +                self.assertTrue(following.completed)\n1229: +                logout = conn.writes.index(b\"exit\\r\")\n1230: +                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n1231: +                self.assertEqual(conn.writes[logout + 1:], [\n1232: +                    (username + \"\\r\").encode(),\n1233: +                    (password + \"\\r\").encode(),\n1234: +                    b\"probe\\r\",\n1235: +                ])\n1236: +                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n1237: +\n1238: +    def test_later_features_wait_for_authentication(self):\n1239: +        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n1240: +        self.run_driver(driver)\n1241: +        self.assertIn(b\"exit\\r\", conn.writes)\n1242: +        self.assertIn(b\"newpass\\r\", conn.writes)\n1243: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1244: +        self.assertFalse(admin.completed)\n1245: +        self.assertFalse(following.completed)\n1246: +        self.assertFalse(cmd.ready)\n1247: +\n1248: +    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n1249: +        for commit_command in (\"next\", \"end\"):\n1250: +            with self.subTest(commit_command=commit_command):\n1251: +                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n1252: +                self.run_driver(driver)\n1253: +                self.assertTrue(cmd.ready)\n1254: +                self.assertTrue(admin.completed)\n1255: +                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n1256: +                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n1257: +                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n1258: +\n1259: +    def test_logout_must_return_to_login(self):\n1260: +        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n1261: +        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n1262: +            self.run_driver(driver)\n1263: +        self.assertFalse(admin.completed)\n1264: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1265: +\n1266: +    def test_rejected_credentials_do_not_start_later_features(self):\n1267: +        conn, _, driver, admin, _ = self.make_stack(reject=True)\n1268: +        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n1269: +            self.run_driver(driver)\n1270: +        self.assertFalse(admin.completed)\n1271: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1272: +        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n1273: +\n1274: +\n1275: +if __name__ == \"__main__\":\n1276: +    unittest.main()\n1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\n1278: new file mode 100644\n1279: index 0000000..2afb43a\n1280: --- /dev/null\n1281: +++ b/fortinet/tests/test_common_recovery.py\n1282: @@ -0,0 +1,292 @@\n1283: +\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n1284: +\n1285: +import sys\n1286: +import unittest\n1287: +from pathlib import Path\n1288: +from unittest.mock import MagicMock\n1289: +\n1290: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1291: +\n1292: +from fortinet.common.cli_commands import (  # noqa: E402\n1293: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n1294: +    EditBlock, SessionLossAction,\n1295: +)\n1296: +from fortinet.common.common import FOSCliState  # noqa: E402\n1297: +from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n1298: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1299: +from fortinet.common.terminal import Data  # noqa: E402\n1300: +\n1301: +\n1302: +IP_COMMAND = \"set ip 10.0.52.4/24\"\n1303: +ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n1304: +\n1305: +\n1306: +class RecordingFeature(Feature):\n1307: +    def __init__(self, commander, block, context_action=None):\n1308: +        super().__init__(None, commander, \"management\")\n1309: +        self.block = block\n1310: +        self.context_action = context_action\n1311: +        self.losses = []\n1312: +        self.attempts = []\n1313: +        self.executed = []\n1314: +\n1315: +    def activate(self):\n1316: +        self.commander.submit_block(self, self.block)\n1317: +\n1318: +    def on_command_dispatched(self, attempt):\n1319: +        super().on_command_dispatched(attempt)\n1320: +        self.attempts.append(attempt)\n1321: +\n1322: +    def on_command_executed(self, attempt, state):\n1323: +        self.executed.append(attempt.spec.line)\n1324: +\n1325: +    def on_context_loss(self, attempt):\n1326: +        self.losses.append(attempt)\n1327: +        if self.context_action is not None:\n1328: +            return self.context_action\n1329: +        return super().on_context_loss(attempt)\n1330: +\n1331: +\n1332: +class RecoveryTests(unittest.TestCase):\n1333: +    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n1334: +                       context_action=None, following=False):\n1335: +        terminal = MagicMock()\n1336: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n1337: +        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1338: +            ip_command, ACCESS_COMMAND,\n1339: +        ])])\n1340: +        feature = RecordingFeature(commander, block, context_action)\n1341: +        features = [feature]\n1342: +        if following:\n1343: +            features.append(RecordingFeature(\n1344: +                commander, CommandSequence(\"following\", [\"get system status\"])\n1345: +            ))\n1346: +        commander.start(features)\n1347: +        return commander, terminal, feature\n1348: +\n1349: +    def prompt(self, commander, context=None):\n1350: +        scope = f\" ({context})\" if context else \"\"\n1351: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n1352: +            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n1353: +        ))\n1354: +\n1355: +    def enter_interface(self, commander):\n1356: +        self.prompt(commander, \"interface\")\n1357: +        self.prompt(commander, \"port1\")\n1358: +\n1359: +    def finish_interface(self, commander):\n1360: +        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n1361: +        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n1362: +        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n1363: +        self.prompt(commander)  # end succeeds.\n1364: +\n1365: +    @staticmethod\n1366: +    def writes(terminal):\n1367: +        return [call.args[0] for call in terminal.write.call_args_list]\n1368: +\n1369: +    def reconnect(self, commander):\n1370: +        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n1371: +        self.prompt(commander)\n1372: +\n1373: +    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n1374: +        commander, terminal, feature = self.make_commander()\n1375: +        self.prompt(commander)\n1376: +        self.enter_interface(commander)\n1377: +        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n1378: +        self.assertEqual(self.writes(terminal), [\n1379: +            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n1380: +            \"config system interface\\r\",\n1381: +        ])\n1382: +        self.assertNotIn(IP_COMMAND, feature.executed)\n1383: +        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n1384: +        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n1385: +        self.enter_interface(commander)\n1386: +        self.finish_interface(commander)\n1387: +        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n1388: +        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n1389: +        self.assertTrue(feature.completed)\n1390: +        self.assertTrue(commander.ready)\n1391: +\n1392: +    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n1393: +        for best_effort in (False, True):\n1394: +            with self.subTest(best_effort=best_effort):\n1395: +                commander, terminal, feature = self.make_commander(\n1396: +                    continue_on_error=best_effort, following=True,\n1397: +                )\n1398: +                self.prompt(commander)\n1399: +                self.enter_interface(commander)\n1400: +                self.prompt(commander)\n1401: +                self.enter_interface(commander)\n1402: +                if best_effort:\n1403: +                    self.prompt(commander)\n1404: +                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1405: +                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1406: +                else:\n1407: +                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1408: +                        self.prompt(commander)\n1409: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n1410: +                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n1411: +                self.assertFalse(feature.completed)\n1412: +\n1413: +    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n1414: +        commander, terminal, feature = self.make_commander()\n1415: +        self.prompt(commander)\n1416: +        self.enter_interface(commander)\n1417: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1418: +        self.reconnect(commander)\n1419: +        self.enter_interface(commander)\n1420: +        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1421: +            self.prompt(commander)\n1422: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n1423: +        self.assertEqual(feature.losses[0].retry_count, 1)\n1424: +\n1425: +    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n1426: +        commander, terminal, _feature = self.make_commander(\n1427: +            continue_on_error=True, following=True,\n1428: +        )\n1429: +        self.prompt(commander)\n1430: +        self.enter_interface(commander)\n1431: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1432: +        self.reconnect(commander)\n1433: +        self.enter_interface(commander)\n1434: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n1435: +        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n1436: +        self.reconnect(commander)\n1437: +        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1438: +        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1439: +\n1440: +    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n1441: +        commander, terminal, _feature = self.make_commander(\n1442: +            continue_on_error=True, following=True,\n1443: +        )\n1444: +        self.prompt(commander)\n1445: +        self.enter_interface(commander)\n1446: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1447: +        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n1448: +        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n1449: +        self.enter_interface(commander)\n1450: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n1451: +        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n1452: +        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n1453: +        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1454: +        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1455: +\n1456: +    def test_each_command_position_gets_one_recovery(self):\n1457: +        commander, terminal, feature = self.make_commander()\n1458: +        self.prompt(commander)\n1459: +        self.enter_interface(commander)\n1460: +        self.prompt(commander)  # First loss: IP command.\n1461: +        self.enter_interface(commander)\n1462: +        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n1463: +        self.prompt(commander)  # Second loss: allowaccess command.\n1464: +        self.enter_interface(commander)\n1465: +        self.finish_interface(commander)\n1466: +        self.assertTrue(feature.completed)\n1467: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n1468: +        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n1469: +\n1470: +    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n1471: +        for explicit_policy in (False, True):\n1472: +            with self.subTest(explicit_policy=explicit_policy):\n1473: +                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n1474: +                commander, terminal, feature = self.make_commander(\n1475: +                    ip_command=IP_COMMAND if explicit_policy else spec,\n1476: +                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n1477: +                )\n1478: +                feature.on_session_loss = MagicMock()\n1479: +                self.prompt(commander)\n1480: +                self.enter_interface(commander)\n1481: +                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n1482: +                    self.prompt(commander)\n1483: +                feature.on_session_loss.assert_not_called()\n1484: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n1485: +\n1486: +    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n1487: +        spec = CommandSpec(\n1488: +            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n1489: +            context_loss=ContextLossAction.RESTART_BLOCK,\n1490: +        )\n1491: +        commander, _terminal, feature = self.make_commander(ip_command=spec)\n1492: +        feature.on_session_loss = MagicMock()\n1493: +        self.prompt(commander)\n1494: +        self.enter_interface(commander)\n1495: +        self.prompt(commander)\n1496: +        self.enter_interface(commander)\n1497: +        self.finish_interface(commander)\n1498: +        self.assertTrue(feature.completed)\n1499: +        feature.on_session_loss.assert_not_called()\n1500: +\n1501: +    def test_partial_scope_is_aborted_once_before_replay(self):\n1502: +        commander, terminal, feature = self.make_commander()\n1503: +        self.prompt(commander)\n1504: +        self.enter_interface(commander)\n1505: +        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n1506: +        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n1507: +        self.prompt(commander)\n1508: +        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n1509: +        self.enter_interface(commander)\n1510: +        self.finish_interface(commander)\n1511: +        self.assertTrue(feature.completed)\n1512: +        self.assertNotIn(\"abort\", feature.executed)\n1513: +        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n1514: +\n1515: +    def test_failed_context_reset_does_not_loop(self):\n1516: +        commander, terminal, _feature = self.make_commander()\n1517: +        self.prompt(commander)\n1518: +        self.enter_interface(commander)\n1519: +        self.prompt(commander, \"interface\")\n1520: +        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n1521: +            self.prompt(commander, \"interface\")\n1522: +        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n1523: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n1524: +\n1525: +    def test_session_loss_during_context_reset_resumes_after_login(self):\n1526: +        commander, terminal, feature = self.make_commander()\n1527: +        self.prompt(commander)\n1528: +        self.enter_interface(commander)\n1529: +        self.prompt(commander, \"interface\")\n1530: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1531: +        self.reconnect(commander)\n1532: +        self.enter_interface(commander)\n1533: +        self.finish_interface(commander)\n1534: +        self.assertTrue(feature.completed)\n1535: +        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n1536: +\n1537: +    def test_cleanup_session_loss_is_bounded(self):\n1538: +        terminal = MagicMock()\n1539: +        commander = FOSCommander(terminal, MagicMock())\n1540: +        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n1541: +        commander.register_cleanup(feature, CleanupAction(\n1542: +            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n1543: +        ))\n1544: +        commander.start([feature])\n1545: +        self.prompt(commander)\n1546: +        self.prompt(commander)  # Begin cleanup after the feature completes.\n1547: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1548: +        self.reconnect(commander)\n1549: +        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1550: +            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1551: +        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n1552: +\n1553: +    def test_newly_submitted_block_resets_retry_allowance(self):\n1554: +        terminal = MagicMock()\n1555: +        commander = FOSCommander(terminal, MagicMock())\n1556: +        feature = StaticFeature(None, commander, \"two-blocks\", [\n1557: +            ConfigBlock(\"system global\", [\"set alias first\"]),\n1558: +            ConfigBlock(\"system global\", [\"set alias second\"]),\n1559: +        ])\n1560: +        commander.start([feature])\n1561: +        self.prompt(commander)\n1562: +        for _index in range(2):\n1563: +            self.prompt(commander, \"global\")\n1564: +            self.prompt(commander)  # Lost context: retry this block.\n1565: +            self.prompt(commander, \"global\")\n1566: +            self.prompt(commander, \"global\")\n1567: +            self.prompt(commander)  # End this block and start the next one.\n1568: +        self.assertTrue(feature.completed)\n1569: +        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n1570: +        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n1571: +\n1572: +\n1573: +if __name__ == \"__main__\":\n1574: +    unittest.main()\n1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\n1576: new file mode 100644\n1577: index 0000000..56ce729\n1578: --- /dev/null\n1579: +++ b/fortinet/tests/test_common_scope_errors.py\n1580: @@ -0,0 +1,154 @@\n1581: +\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n1582: +\n1583: +import sys\n1584: +import unittest\n1585: +from pathlib import Path\n1586: +from unittest.mock import MagicMock\n1587: +\n1588: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1589: +\n1590: +from fortinet.common.cli_commands import (  # noqa: E402\n1591: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n1592: +)\n1593: +from fortinet.common.common import FOSCliState  # noqa: E402\n1594: +from fortinet.common.features.base import Feature  # noqa: E402\n1595: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1596: +from fortinet.common.terminal import Data  # noqa: E402\n1597: +\n1598: +\n1599: +class RecordingFeature(Feature):\n1600: +    def __init__(self, commander, name, commands):\n1601: +        super().__init__(None, commander, name)\n1602: +        self.commands = commands\n1603: +        self.executed = []\n1604: +\n1605: +    def activate(self):\n1606: +        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n1607: +\n1608: +    def on_command_executed(self, attempt, state):\n1609: +        self.executed.append(attempt.spec.line)\n1610: +\n1611: +\n1612: +class ScopeCommitFailureTests(unittest.TestCase):\n1613: +    @staticmethod\n1614: +    def prompt(commander, context=None, output=b\"\"):\n1615: +        scope = f\" ({context})\" if context else \"\"\n1616: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n1617: +            output + f\"fw{scope} #\".encode()\n1618: +        ))\n1619: +\n1620: +    @staticmethod\n1621: +    def writes(terminal):\n1622: +        return [call.args[0] for call in terminal.write.call_args_list]\n1623: +\n1624: +    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n1625: +        for close in (\"next\", \"end\"):\n1626: +            for capture in (False, True):\n1627: +                for best_effort in (False, True):\n1628: +                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n1629: +                        terminal = MagicMock()\n1630: +                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n1631: +                        feature = RecordingFeature(commander, \"commit\", [\n1632: +                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n1633: +                            \"set must-not-run 1\",\n1634: +                        ])\n1635: +                        feature.on_context_loss = MagicMock()\n1636: +                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n1637: +                        commander.start([feature, following])\n1638: +                        self.prompt(commander, \"port1\")\n1639: +                        # The failure code can span multiple serial reads.\n1640: +                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n1641: +                            data = Data(chunk)\n1642: +                            commander.on_output(data)\n1643: +                            self.assertTrue(data.discarded)\n1644: +                        if best_effort:\n1645: +                            self.prompt(commander, \"interface\")\n1646: +                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n1647: +                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n1648: +                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n1649: +                        else:\n1650: +                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n1651: +                                self.prompt(commander, \"interface\")\n1652: +                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n1653: +                        feature.on_context_loss.assert_not_called()\n1654: +                        self.assertEqual(feature.executed, [])\n1655: +                        self.assertFalse(feature.completed)\n1656: +\n1657: +    def test_closing_failure_with_same_prompt_still_ejects(self):\n1658: +        for code in (\"0\", \"7\", \"-61\"):\n1659: +            for suffix in (\"\", \".\"):\n1660: +                with self.subTest(code=code, suffix=suffix):\n1661: +                    terminal = MagicMock()\n1662: +                    commander = FOSCommander(terminal, MagicMock())\n1663: +                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n1664: +                    commander.start([feature])\n1665: +                    self.prompt(commander, \"port1\")\n1666: +                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n1667: +                        self.prompt(\n1668: +                            commander, \"port1\",\n1669: +                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n1670: +                        )\n1671: +                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n1672: +\n1673: +    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n1674: +        for capture in (False, True):\n1675: +            with self.subTest(capture=capture):\n1676: +                terminal = MagicMock()\n1677: +                commander = FOSCommander(terminal, MagicMock())\n1678: +                feature = RecordingFeature(commander, \"configure\", [\n1679: +                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1680: +                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n1681: +                    ])]),\n1682: +                ])\n1683: +                commander.start([feature])\n1684: +                self.prompt(commander)\n1685: +                self.prompt(commander, \"interface\")\n1686: +                self.prompt(commander, \"port1\")\n1687: +                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n1688: +                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n1689: +                self.prompt(commander, \"interface\")\n1690: +                self.prompt(commander)\n1691: +                self.assertTrue(feature.completed)\n1692: +                self.assertTrue(commander.ready)\n1693: +                self.assertEqual(commander.feature_errors, ())\n1694: +\n1695: +    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n1696: +        for best_effort in (False, True):\n1697: +            with self.subTest(best_effort=best_effort):\n1698: +                terminal = MagicMock()\n1699: +                commander = FOSCommander(terminal, MagicMock(), best_effort)\n1700: +                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n1701: +                following = RecordingFeature(commander, \"following\", [\"get status\"])\n1702: +                commander.register_cleanup(feature, CleanupAction(\n1703: +                    \"close\", CommandSequence(\"close\", [\"end\"]),\n1704: +                ))\n1705: +                commander.start([feature, following])\n1706: +                self.prompt(commander)\n1707: +                self.prompt(commander)\n1708: +                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n1709: +                if best_effort:\n1710: +                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n1711: +                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n1712: +                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n1713: +                else:\n1714: +                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n1715: +                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n1716: +                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n1717: +\n1718: +    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n1719: +        terminal = MagicMock()\n1720: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n1721: +        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n1722: +            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n1723: +            expected_completion_state=FOSCliState.CMD_PROMPT,\n1724: +        )])\n1725: +        commander.start([feature])\n1726: +        self.prompt(commander, \"interface\")\n1727: +        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n1728: +            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n1729: +        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n1730: +        self.assertFalse(feature.completed)\n1731: +\n1732: +\n1733: +if __name__ == \"__main__\":\n1734: +    unittest.main()\n1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\n1736: index 1e31693..d633771 100644\n1737: --- a/fortinet/tests/test_common_stack_boundaries.py\n1738: +++ b/fortinet/tests/test_common_stack_boundaries.py\n1739: @@ -38,15 +38,15 @@ class BoundaryFeature(Feature):\n1740:  \n1741:      def on_session_loss(self, attempt):\n1742:          return SessionLossAction.CONTINUE\n1743:  \n1744:  \n1745: -def make_stack(spec, response, *, allow_recovery=False):\n1746: +def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n1747:      logger = MagicMock()\n1748:      connection = SerialConnection({\n1749:          b\"admin\\r\": b\"Password:\",\n1750: -        b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1751: +        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n1752:          b\"probe\\r\": response,\n1753:      })\n1754:      terminal = Terminal(connection, logger, default_wait=\"fw #\")\n1755:      commander = FOSCommander(terminal, logger)\n1756:      feature = BoundaryFeature(commander, spec)\n1757: @@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):\n1758:      response = (\n1759:          (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n1760:          .encode()\n1761:      )\n1762:      spec = CommandSpec(\"probe\", capture_output=True)\n1763: -    connection, terminal, commander, driver, feature, states = make_stack(spec, response)\n1764: +    connection, terminal, commander, driver, feature, states = make_stack(\n1765: +        spec, response, initial_prompt=prompt.encode()\n1766: +    )\n1767:      try:\n1768:          with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n1769:                  patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1770:              driver.process_state()\n1771:          assert commander.ready\n1772: @@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b\"\", *, recover=False):\n1773:          completion = (state,)\n1774:      connection, terminal, commander, driver, feature, states = make_stack(\n1775:          CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n1776:          response,\n1777:          allow_recovery=recover,\n1778: +        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n1779:      )\n1780:      try:\n1781:          with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n1782:                  patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1783:              driver.process_state()\n1784: @@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):\n1785:              self.assertFalse(feature.completed)\n1786:              self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n1787:          finally:\n1788:              terminal.close()\n1789:  \n1790: -    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):\n1791: +    def test_idle_read_exposes_retained_prompt_newline(self):\n1792:          connection, terminal, commander, driver, feature, states = make_stack(\n1793:              CommandSpec(\"probe\", capture_output=True), None\n1794:          )\n1795:          try:\n1796:              with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n1797:                      patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n1798:                  driver.process_state()\n1799:              self.assertIn(FOSCliState.TN_TIMEOUT, states)\n1800: -            self.assertEqual(bytes(feature.current_attempt.output), b\"\")\n1801: +            # The login response ended with a newline after the matched CLI\n1802: +            # prompt. Full-buffer timeout inspection exposes that real byte.\n1803: +            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n1804:              self.assertTrue(commander.busy)\n1805:          finally:\n1806:              terminal.close()\n1807:  \n1808:      def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n1809:          command_echo = b\"fw (global) # probe\\r\\n\"\n1810:          payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n1811:          response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n1812:          connection, terminal, commander, driver, feature, states = make_stack(\n1813: -            CommandSpec(\"probe\", capture_output=True), response\n1814: +            CommandSpec(\"probe\", capture_output=True), response,\n1815: +            initial_prompt=b\"fw (global) #\",\n1816:          )\n1817:          try:\n1818:              with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n1819:                      patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1820:                  driver.process_state()\n1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\n1822: index 74d6ef7..56346ea 100644\n1823: --- a/fortinet/tests/test_common_stack_parsing.py\n1824: +++ b/fortinet/tests/test_common_stack_parsing.py\n1825: @@ -7,11 +7,13 @@ from pathlib import Path\n1826:  from unittest.mock import MagicMock\n1827:  \n1828:  REPO_ROOT = Path(__file__).resolve().parents[2]\n1829:  sys.path.insert(0, str(REPO_ROOT))\n1830:  \n1831: -from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402\n1832: +from fortinet.common.cli_commands import (  # noqa: E402\n1833: +    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n1834: +)\n1835:  from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n1836:  from fortinet.common.features.base import Feature  # noqa: E402\n1837:  from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n1838:  from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1839:  from fortinet.common.terminal import Terminal  # noqa: E402\n1840: @@ -35,10 +37,12 @@ class SerialConnection:\n1841:  \n1842:      def write(self, data):\n1843:          data = bytes(data)\n1844:          self.writes.append(data)\n1845:          response = self._responses.get(data)\n1846: +        if callable(response):\n1847: +            response = response()\n1848:          if response:\n1849:              chunks = response if isinstance(response, (tuple, list)) else (response,)\n1850:              for chunk in chunks:\n1851:                  if chunk:\n1852:                      self._incoming.put(bytes(chunk))\n1853: @@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):\n1854:          self.assertEqual(bytes(terminal._buffer), b\"\")\n1855:  \n1856:      def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n1857:          responses = {\n1858:              b\"admin\\r\": b\"Password:\",\n1859: -            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1860: +            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n1861:              b\"get system status\\r\": (\n1862:                  b\"fw (global) # get system status\\r\\n\"\n1863:                  b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n1864:                  b\"--More--\\r\\n\"\n1865:                  b\"Serial-Number: FGVMTEST\\r\\n\"\n1866: @@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):\n1867:          self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n1868:          self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n1869:          self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n1870:          self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n1871:  \n1872: +    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n1873: +        ip_responses = iter([\n1874: +            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n1875: +            b\"fw (port1) (Interim)#\\r\\n\",\n1876: +        ])\n1877: +        responses = {\n1878: +            b\"admin\\r\": b\"Password:\",\n1879: +            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n1880: +            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n1881: +            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n1882: +            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n1883: +            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n1884: +            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n1885: +            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n1886: +        }\n1887: +        feature_ref = []\n1888: +\n1889: +        def configured(commander):\n1890: +            feature = RecordingFeature(commander, \"management\", [\n1891: +                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1892: +                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n1893: +                ])]),\n1894: +            ])\n1895: +            feature_ref.append(feature)\n1896: +            return [feature]\n1897: +\n1898: +        connection, terminal, commander, driver = self.make_stack(configured, responses)\n1899: +        try:\n1900: +            driver.process_state()\n1901: +            self.assertTrue(commander.ready)\n1902: +            self.assertTrue(feature_ref[0].completed)\n1903: +            self.assertEqual(connection.writes, [\n1904: +                b\"admin\\r\", b\"secret\\r\",\n1905: +                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n1906: +                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n1907: +                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n1908: +            ])\n1909: +        finally:\n1910: +            terminal.close()\n1911: +\n1912: +    def test_failed_next_ejects_before_end_through_serial_driver(self):\n1913: +        responses = {\n1914: +            b\"admin\\r\": b\"Password:\",\n1915: +            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1916: +            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n1917: +            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n1918: +            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n1919: +            b\"next\\r\": (\n1920: +                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n1921: +            ),\n1922: +        }\n1923: +        feature_ref = []\n1924: +\n1925: +        def configured(commander):\n1926: +            feature = RecordingFeature(commander, \"management\", [\n1927: +                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n1928: +            ])\n1929: +            feature_ref.append(feature)\n1930: +            return [feature]\n1931: +\n1932: +        connection, terminal, commander, driver = self.make_stack(configured, responses)\n1933: +        try:\n1934: +            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n1935: +                driver.process_state()\n1936: +            self.assertEqual(connection.writes, [\n1937: +                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n1938: +                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n1939: +            ])\n1940: +            self.assertFalse(feature_ref[0].completed)\n1941: +            self.assertFalse(commander.ready)\n1942: +        finally:\n1943: +            terminal.close()\n1944: +\n1945:  \n1946:  if __name__ == \"__main__\":\n1947:      unittest.main()\n1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\n1949: index 4c0a37b..be7eab4 100644\n1950: --- a/fortinet/tests/test_common_terminal_driver.py\n1951: +++ b/fortinet/tests/test_common_terminal_driver.py\n1952: @@ -9,12 +9,16 @@ from contextlib import contextmanager\n1953:  from unittest.mock import MagicMock, patch\n1954:  \n1955:  REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n1956:  sys.path.insert(0, str(REPO_ROOT))\n1957:  \n1958: -from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n1959: -from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n1960: +from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n1961: +from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n1962: +from fortinet.common.fos_cli_driver import (  # noqa: E402\n1963: +    FOSCliDriver,\n1964: +    KernelPanicError,\n1965: +)\n1966:  from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n1967:  \n1968:  \n1969:  class ByteQueueTests(unittest.TestCase):\n1970:      def test_put_get_close_timeout_and_failure(self):\n1971: @@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):\n1972:          terminal._buffer_limit = 5\n1973:          with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n1974:              terminal._enforce_buffer_limit()\n1975:          terminal._logger.error.assert_called_once()\n1976:  \n1977: +    def test_timeout_preserves_partial_token_for_a_later_read(self):\n1978: +        terminal = self.terminal_with_data(b\"Login incor\")\n1979: +        pattern = rb\"(?m)^Login incorrect\\r?$\"\n1980: +        index, match, output = terminal.expect([pattern], timeout=0.001)\n1981: +        self.assertEqual((index, match), (-1, None))\n1982: +        self.assertEqual(bytes(output), b\"Login incor\")\n1983: +        # Inspection without discard keeps the partial token, including when\n1984: +        # another wait expires without receiving any more bytes.\n1985: +        _, _, output = terminal.expect([pattern], timeout=0)\n1986: +        self.assertEqual(bytes(output), b\"Login incor\")\n1987: +        terminal._read_queue.put(b\"rect\\n\")\n1988: +        index, match, output = terminal.expect([pattern], timeout=0.1)\n1989: +        self.assertEqual(index, 0)\n1990: +        self.assertEqual(match.group(), b\"Login incorrect\")\n1991: +        self.assertEqual(bytes(output), b\"Login incorrect\")\n1992: +        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n1993: +\n1994: +    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n1995: +        terminal = self.terminal_with_data(b\"Verifying pass\")\n1996: +        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n1997: +        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n1998: +\n1999: +        terminal._read_queue.put(b\"word...\\n\")\n2000: +        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n2001: +        self.assertIsNone(match)\n2002: +        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n2003: +        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n2004: +        output.discard()\n2005: +        self.assertEqual(bytes(terminal._buffer), b\"\")\n2006: +\n2007: +    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n2008: +        prefix = b\"\\nVerifying password...\\n\"\n2009: +        chunk = b\"admin\\nadmin\\n\"\n2010: +        terminal = self.terminal_with_data(chunk)\n2011: +        terminal._buffer.extend(prefix)\n2012: +\n2013: +        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n2014: +        self.assertEqual(bytes(output), prefix + chunk)\n2015: +        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n2016: +        attempt.on_output(output)\n2017: +\n2018: +        self.assertEqual(bytes(attempt.output), prefix + chunk)\n2019: +        self.assertEqual(bytes(terminal._buffer), b\"\")\n2020: +        terminal._logger.warning.assert_not_called()\n2021: +\n2022:      def test_suppression_is_nested_and_restores_context(self):\n2023:          @contextmanager\n2024:          def context():\n2025:              events.append(\"enter\")\n2026:              try:\n2027: @@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):\n2028:          with self.assertRaisesRegex(OSError, \"serial failed\"):\n2029:              queue.get(0)\n2030:          logger.exception.assert_called_once()\n2031:          with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n2032:              self.assertEqual(terminal_buffer_limit_bytes(), 32)\n2033: -        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n2034: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n2035: +            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n2036: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n2037:              with self.assertRaises(ValueError):\n2038:                  terminal_buffer_limit_bytes()\n2039:  \n2040: +    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n2041: +        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n2042: +            with self.subTest(env_name=env_name):\n2043: +                terminal = self.terminal_with_data(b\"matched\")\n2044: +                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n2045: +                    terminal.expect([b\"matched\"], timeout=0.1)\n2046: +                terminal._logger.log.assert_called_once_with(\n2047: +                    TRACE_LEVEL,\n2048: +                    \"buffer: bytearray(b'matched')\",\n2049: +                )\n2050: +\n2051:  \n2052:  class DriverTests(unittest.TestCase):\n2053:      def make_driver(self, *, allow_recovery=False):\n2054:          terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n2055:          commander.ready = False\n2056: @@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):\n2057:          self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n2058:          terminal.expect.return_value = (-1, None, Data(b\"\"))\n2059:          self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n2060:          driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n2061:  \n2062: +    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n2063: +        driver, _, _, logger, *_ = self.make_driver()\n2064: +        terminal = Terminal(MagicMock(), logger)\n2065: +        terminal._ensure_reader = lambda: None\n2066: +        terminal._read_queue.put(b\"partial token\")\n2067: +        driver._terminal = terminal\n2068: +\n2069: +        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n2070: +            state, output, matched = driver._next_state()\n2071: +            self.assertEqual(state, FOSCliState.UNKNOWN)\n2072: +            self.assertEqual(bytes(output), b\"partial token\")\n2073: +            self.assertFalse(matched)\n2074: +            state, output, matched = driver._next_state()\n2075: +            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n2076: +            self.assertEqual(bytes(output), b\"partial token\")\n2077: +            self.assertFalse(matched)\n2078: +\n2079: +    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n2080: +        driver, terminal, commander, *_ = self.make_driver()\n2081: +        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n2082: +        panic = (\n2083: +            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n2084: +            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n2085: +        )\n2086: +\n2087: +        self.assertIsNone(\n2088: +            re.search(\n2089: +                pattern,\n2090: +                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n2091: +            )\n2092: +        )\n2093: +        match = re.search(pattern, panic)\n2094: +        self.assertIsNotNone(match)\n2095: +        terminal.expect.return_value = (\n2096: +            FOSCliState.KERNEL_PANIC.value,\n2097: +            match,\n2098: +            Data(panic),\n2099: +        )\n2100: +\n2101: +        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n2102: +            driver.process_state()\n2103: +\n2104: +        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n2105: +\n2106:  \n2107:  if __name__ == \"__main__\":\n2108:      unittest.main()\n\n(End of file - total 2108 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+        def activate_desired():\n+            driver.remember_current_credentials()\n+            credentials.username = username\n+            credentials.password = password\n+\n+        vm = SimpleNamespace(\n+            desired_credentials=Credentials(username, password),\n+            activate_desired_credentials=activate_desired,\n+        )\n+        admin = CredentialsFeature(vm, commander)\n+        following = RecordingFeature(commander, \"following\", [\"probe\"])\n+        commander.start([admin, following])\n+        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n+        return connection, commander, driver, admin, following\n+\n+    def run_driver(self, driver):\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n+                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n+            driver.process_state()\n+",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+        def activate_desired():\n+            driver.remember_current_credentials()\n+            credentials.username = username\n+            credentials.password = password\n+\n+        vm = SimpleNamespace(\n+            desired_credentials=Credentials(username, password),\n+            activate_desired_credentials=activate_desired,\n+        )\n+        admin = CredentialsFeature(vm, commander)\n+        following = RecordingFeature(commander, \"following\", [\"probe\"])\n+        commander.start([admin, following])\n+        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n+        return connection, commander, driver, admin, following\n+\n+    def run_driver(self, driver):\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n+                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n+            driver.process_state()\n+\n+    def test_logout_and_relogin_after_committing_credentials(self):\n+        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n+                                   (\"operator\", \"newpass\")):\n+            with self.subTest(username=username, password_set=bool(password)):\n+                conn, cmd, driver, admin, following = self.make_stack(\n+                    username=username, password=password,\n+                )\n+                self.run_driver(driver)\n+                self.assertTrue(cmd.ready)\n+                self.assertTrue(admin.completed)\n+                self.assertTrue(following.completed)\n+                logout = conn.writes.index(b\"exit\\r\")\n+                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n+                self.assertEqual(conn.writes[logout + 1:], [\n+                    (username + \"\\r\").encode(),\n+                    (password + \"\\r\").encode(),\n+                    b\"probe\\r\",\n+                ])\n+                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n+\n+    def test_later_features_wait_for_authentication(self):\n+        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n+        self.run_driver(driver)\n+        self.assertIn(b\"exit\\r\", conn.writes)\n+        self.assertIn(b\"newpass\\r\", conn.writes)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+        self.assertFalse(admin.completed)\n+        self.assertFalse(following.completed)\n+        self.assertFalse(cmd.ready)\n+\n+    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n+        for commit_command in (\"next\", \"end\"):\n+            with self.subTest(commit_command=commit_command):\n+                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n+                self.run_driver(driver)\n+                self.assertTrue(cmd.ready)\n+                self.assertTrue(admin.completed)\n+                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n+                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n+                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n+\n+    def test_logout_must_return_to_login(self):\n+        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n+        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n+            self.run_driver(driver)\n+        self.assertFalse(admin.completed)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+\n+    def test_rejected_credentials_do_not_start_later_features(self):\n+        conn, _, driver, admin, _ = self.make_stack(reject=True)\n+        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n+            self.run_driver(driver)\n+        self.assertFalse(admin.completed)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\nnew file mode 100644\nindex 0000000..2afb43a\n--- /dev/null\n+++ b/fortinet/tests/test_common_recovery.py\n@@ -0,0 +1,292 @@\n+\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n+    EditBlock, SessionLossAction,\n+)\n+from fortinet.common.common import FOSCliState  # noqa: E402\n+from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n+from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n+from fortinet.common.terminal import Data  # noqa: E402\n+\n+\n+IP_COMMAND = \"set ip 10.0.52.4/24\"\n+ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n+\n+\n+class RecordingFeature(Feature):\n+    def __init__(self, commander, block, context_action=None):\n+        super().__init__(None, commander, \"management\")\n+        self.block = block\n+        self.context_action = context_action\n+        self.losses = []\n+        self.attempts = []\n+        self.executed = []\n+\n+    def activate(self):\n+        self.commander.submit_block(self, self.block)\n+\n+    def on_command_dispatched(self, attempt):\n+        super().on_command_dispatched(attempt)\n+        self.attempts.append(attempt)\n+\n+    def on_command_executed(self, attempt, state):\n+        self.executed.append(attempt.spec.line)\n+\n+    def on_context_loss(self, attempt):\n+        self.losses.append(attempt)\n+        if self.context_action is not None:\n+            return self.context_action\n+        return super().on_context_loss(attempt)\n+\n+\n+class RecoveryTests(unittest.TestCase):\n+    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n+                       context_action=None, following=False):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n+        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+            ip_command, ACCESS_COMMAND,\n+        ])])\n+        feature = RecordingFeature(commander, block, context_action)\n+        features = [feature]\n+        if following:\n+            features.append(RecordingFeature(\n+                commander, CommandSequence(\"following\", [\"get system status\"])\n+            ))\n+        commander.start(features)\n+        return commander, terminal, feature\n+\n+    def prompt(self, commander, context=None):\n+        scope = f\" ({context})\" if context else \"\"\n+        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n+            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n+        ))\n+\n+    def enter_interface(self, commander):\n+        self.prompt(commander, \"interface\")\n+        self.prompt(commander, \"port1\")\n+\n+    def finish_interface(self, commander):\n+        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n+        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n+        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n+        self.prompt(commander)  # end succeeds.\n+\n+    @staticmethod\n+    def writes(terminal):\n+        return [call.args[0] for call in terminal.write.call_args_list]\n+\n+    def reconnect(self, commander):\n+        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n+        self.prompt(commander)\n+\n+    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n+        self.assertEqual(self.writes(terminal), [\n+            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n+            \"config system interface\\r\",\n+        ])\n+        self.assertNotIn(IP_COMMAND, feature.executed)\n+        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n+        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n+        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n+        self.assertTrue(feature.completed)\n+        self.assertTrue(commander.ready)\n+\n+    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n+        for best_effort in (False, True):\n+            with self.subTest(best_effort=best_effort):\n+                commander, terminal, feature = self.make_commander(\n+                    continue_on_error=best_effort, following=True,\n+                )\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                if best_effort:\n+                    self.prompt(commander)\n+                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+                else:\n+                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+                        self.prompt(commander)\n+                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n+                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n+                self.assertFalse(feature.completed)\n+\n+    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+            self.prompt(commander)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n+        self.assertEqual(feature.losses[0].retry_count, 1)\n+\n+    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n+        commander, terminal, _feature = self.make_commander(\n+            continue_on_error=True, following=True,\n+        )\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n+        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n+        self.reconnect(commander)\n+        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+\n+    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n+        commander, terminal, _feature = self.make_commander(\n+            continue_on_error=True, following=True,\n+        )\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n+        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n+        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n+        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n+        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+\n+    def test_each_command_position_gets_one_recovery(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)  # First loss: IP command.\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n+        self.prompt(commander)  # Second loss: allowaccess command.\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n+        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n+\n+    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n+        for explicit_policy in (False, True):\n+            with self.subTest(explicit_policy=explicit_policy):\n+                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n+                commander, terminal, feature = self.make_commander(\n+                    ip_command=IP_COMMAND if explicit_policy else spec,\n+                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n+                )\n+                feature.on_session_loss = MagicMock()\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n+                    self.prompt(commander)\n+                feature.on_session_loss.assert_not_called()\n+                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n+\n+    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n+        spec = CommandSpec(\n+            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n+            context_loss=ContextLossAction.RESTART_BLOCK,\n+        )\n+        commander, _terminal, feature = self.make_commander(ip_command=spec)\n+        feature.on_session_loss = MagicMock()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        feature.on_session_loss.assert_not_called()\n+\n+    def test_partial_scope_is_aborted_once_before_replay(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n+        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n+        self.prompt(commander)\n+        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertNotIn(\"abort\", feature.executed)\n+        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n+\n+    def test_failed_context_reset_does_not_loop(self):\n+        commander, terminal, _feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")\n+        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n+            self.prompt(commander, \"interface\")\n+        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n+\n+    def test_session_loss_during_context_reset_resumes_after_login(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n+\n+    def test_cleanup_session_loss_is_bounded(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock())\n+        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n+        commander.register_cleanup(feature, CleanupAction(\n+            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n+        ))\n+        commander.start([feature])\n+        self.prompt(commander)\n+        self.prompt(commander)  # Begin cleanup after the feature completes.\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n+\n+    def test_newly_submitted_block_resets_retry_allowance(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock())\n+        feature = StaticFeature(None, commander, \"two-blocks\", [\n+            ConfigBlock(\"system global\", [\"set alias first\"]),\n+            ConfigBlock(\"system global\", [\"set alias second\"]),\n+        ])\n+        commander.start([feature])\n+        self.prompt(commander)\n+        for _index in range(2):\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander)  # Lost context: retry this block.\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander)  # End this block and start the next one.\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n+        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\nnew file mode 100644\nindex 0000000..56ce729\n--- /dev/null\n+++ b/fortinet/tests/test_common_scope_errors.py\n@@ -0,0 +1,154 @@\n+\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n+)\n+from fortinet.common.common import FOSCliState  # noqa: E402\n+from fortinet.common.features.base import Feature  # noqa: E402\n+from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n+from fortinet.common.terminal import Data  # noqa: E402\n+\n+\n+class RecordingFeature(Feature):\n+    def __init__(self, commander, name, commands):\n+        super().__init__(None, commander, name)\n+        self.commands = commands\n+        self.executed = []\n+\n+    def activate(self):\n+        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n+\n+    def on_command_executed(self, attempt, state):\n+        self.executed.append(attempt.spec.line)\n+\n+\n+class ScopeCommitFailureTests(unittest.TestCase):\n+    @staticmethod\n+    def prompt(commander, context=None, output=b\"\"):\n+        scope = f\" ({context})\" if context else \"\"\n+        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n+            output + f\"fw{scope} #\".encode()\n+        ))\n+\n+    @staticmethod\n+    def writes(terminal):\n+        return [call.args[0] for call in terminal.write.call_args_list]\n+\n+    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n+        for close in (\"next\", \"end\"):\n+            for capture in (False, True):\n+                for best_effort in (False, True):\n+                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n+                        terminal = MagicMock()\n+                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n+                        feature = RecordingFeature(commander, \"commit\", [\n+                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n+                            \"set must-not-run 1\",\n+                        ])\n+                        feature.on_context_loss = MagicMock()\n+                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n+                        commander.start([feature, following])\n+                        self.prompt(commander, \"port1\")\n+                        # The failure code can span multiple serial reads.\n+                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n+                            data = Data(chunk)\n+                            commander.on_output(data)\n+                            self.assertTrue(data.discarded)\n+                        if best_effort:\n+                            self.prompt(commander, \"interface\")\n+                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n+                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n+                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n+                        else:\n+                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n+                                self.prompt(commander, \"interface\")\n+                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n+                        feature.on_context_loss.assert_not_called()\n+                        self.assertEqual(feature.executed, [])\n+                        self.assertFalse(feature.completed)\n+\n+    def test_closing_failure_with_same_prompt_still_ejects(self):\n+        for code in (\"0\", \"7\", \"-61\"):\n+            for suffix in (\"\", \".\"):\n+                with self.subTest(code=code, suffix=suffix):\n+                    terminal = MagicMock()\n+                    commander = FOSCommander(terminal, MagicMock())\n+                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n+                    commander.start([feature])\n+                    self.prompt(commander, \"port1\")\n+                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n+                        self.prompt(\n+                            commander, \"port1\",\n+                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n+                        )\n+                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n+\n+    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n+        for capture in (False, True):\n+            with self.subTest(capture=capture):\n+                terminal = MagicMock()\n+                commander = FOSCommander(terminal, MagicMock())\n+                feature = RecordingFeature(commander, \"configure\", [\n+                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n+                    ])]),\n+                ])\n+                commander.start([feature])\n+                self.prompt(commander)\n+                self.prompt(commander, \"interface\")\n+                self.prompt(commander, \"port1\")\n+                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n+                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n+                self.prompt(commander, \"interface\")\n+                self.prompt(commander)\n+                self.assertTrue(feature.completed)\n+                self.assertTrue(commander.ready)\n+                self.assertEqual(commander.feature_errors, ())\n+\n+    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n+        for best_effort in (False, True):\n+            with self.subTest(best_effort=best_effort):\n+                terminal = MagicMock()\n+                commander = FOSCommander(terminal, MagicMock(), best_effort)\n+                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n+                following = RecordingFeature(commander, \"following\", [\"get status\"])\n+                commander.register_cleanup(feature, CleanupAction(\n+                    \"close\", CommandSequence(\"close\", [\"end\"]),\n+                ))\n+                commander.start([feature, following])\n+                self.prompt(commander)\n+                self.prompt(commander)\n+                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n+                if best_effort:\n+                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n+                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n+                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n+                else:\n+                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n+                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n+                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n+\n+    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n+        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n+            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n+            expected_completion_state=FOSCliState.CMD_PROMPT,\n+        )])\n+        commander.start([feature])\n+        self.prompt(commander, \"interface\")\n+        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n+            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n+        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n+        self.assertFalse(feature.completed)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\nindex 1e31693..d633771 100644\n--- a/fortinet/tests/test_common_stack_boundaries.py\n+++ b/fortinet/tests/test_common_stack_boundaries.py\n@@ -38,15 +38,15 @@ class BoundaryFeature(Feature):\n \n     def on_session_loss(self, attempt):\n         return SessionLossAction.CONTINUE\n \n \n-def make_stack(spec, response, *, allow_recovery=False):\n+def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n     logger = MagicMock()\n     connection = SerialConnection({\n         b\"admin\\r\": b\"Password:\",\n-        b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n         b\"probe\\r\": response,\n     })\n     terminal = Terminal(connection, logger, default_wait=\"fw #\")\n     commander = FOSCommander(terminal, logger)\n     feature = BoundaryFeature(commander, spec)\n@@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):\n     response = (\n         (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n         .encode()\n     )\n     spec = CommandSpec(\"probe\", capture_output=True)\n-    connection, terminal, commander, driver, feature, states = make_stack(spec, response)\n+    connection, terminal, commander, driver, feature, states = make_stack(\n+        spec, response, initial_prompt=prompt.encode()\n+    )\n     try:\n         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n             driver.process_state()\n         assert commander.ready\n@@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b\"\", *, recover=False):\n         completion = (state,)\n     connection, terminal, commander, driver, feature, states = make_stack(\n         CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n         response,\n         allow_recovery=recover,\n+        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n     )\n     try:\n         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n             driver.process_state()\n@@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):\n             self.assertFalse(feature.completed)\n             self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n         finally:\n             terminal.close()\n \n-    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):\n+    def test_idle_read_exposes_retained_prompt_newline(self):\n         connection, terminal, commander, driver, feature, states = make_stack(\n             CommandSpec(\"probe\", capture_output=True), None\n         )\n         try:\n             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n                 driver.process_state()\n             self.assertIn(FOSCliState.TN_TIMEOUT, states)\n-            self.assertEqual(bytes(feature.current_attempt.output), b\"\")\n+            # The login response ended with a newline after the matched CLI\n+            # prompt. Full-buffer timeout inspection exposes that real byte.\n+            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n             self.assertTrue(commander.busy)\n         finally:\n             terminal.close()\n \n     def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n         command_echo = b\"fw (global) # probe\\r\\n\"\n         payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n         response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n         connection, terminal, commander, driver, feature, states = make_stack(\n-            CommandSpec(\"probe\", capture_output=True), response\n+            CommandSpec(\"probe\", capture_output=True), response,\n+            initial_prompt=b\"fw (global) #\",\n         )\n         try:\n             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                 driver.process_state()\ndiff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\nindex 74d6ef7..56346ea 100644\n--- a/fortinet/tests/test_common_stack_parsing.py\n+++ b/fortinet/tests/test_common_stack_parsing.py\n@@ -7,11 +7,13 @@ from pathlib import Path\n from unittest.mock import MagicMock\n \n REPO_ROOT = Path(__file__).resolve().parents[2]\n sys.path.insert(0, str(REPO_ROOT))\n \n-from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n+)\n from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n from fortinet.common.features.base import Feature  # noqa: E402\n from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n from fortinet.common.terminal import Terminal  # noqa: E402\n@@ -35,10 +37,12 @@ class SerialConnection:\n \n     def write(self, data):\n         data = bytes(data)\n         self.writes.append(data)\n         response = self._responses.get(data)\n+        if callable(response):\n+            response = response()\n         if response:\n             chunks = response if isinstance(response, (tuple, list)) else (response,)\n             for chunk in chunks:\n                 if chunk:\n                     self._incoming.put(bytes(chunk))\n@@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):\n         self.assertEqual(bytes(terminal._buffer), b\"\")\n \n     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n         responses = {\n             b\"admin\\r\": b\"Password:\",\n-            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n             b\"get system status\\r\": (\n                 b\"fw (global) # get system status\\r\\n\"\n                 b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n                 b\"--More--\\r\\n\"\n                 b\"Serial-Number: FGVMTEST\\r\\n\"\n@@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):\n         self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n         self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n \n+    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n+        ip_responses = iter([\n+            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n+            b\"fw (port1) (Interim)#\\r\\n\",\n+        ])\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n+            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n+            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n+            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n+            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n+            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n+            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n+        }\n+        feature_ref = []\n+\n+        def configured(commander):\n+            feature = RecordingFeature(commander, \"management\", [\n+                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n+                ])]),\n+            ])\n+            feature_ref.append(feature)\n+            return [feature]\n+\n+        connection, terminal, commander, driver = self.make_stack(configured, responses)\n+        try:\n+            driver.process_state()\n+            self.assertTrue(commander.ready)\n+            self.assertTrue(feature_ref[0].completed)\n+            self.assertEqual(connection.writes, [\n+                b\"admin\\r\", b\"secret\\r\",\n+                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n+                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n+                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n+            ])\n+        finally:\n+            terminal.close()\n+\n+    def test_failed_next_ejects_before_end_through_serial_driver(self):\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n+            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n+            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n+            b\"next\\r\": (\n+                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n+            ),\n+        }\n+        feature_ref = []\n+\n+        def configured(commander):\n+            feature = RecordingFeature(commander, \"management\", [\n+                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n+            ])\n+            feature_ref.append(feature)\n+            return [feature]\n+\n+        connection, terminal, commander, driver = self.make_stack(configured, responses)\n+        try:\n+            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n+                driver.process_state()\n+            self.assertEqual(connection.writes, [\n+                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n+                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n+            ])\n+            self.assertFalse(feature_ref[0].completed)\n+            self.assertFalse(commander.ready)\n+        finally:\n+            terminal.close()\n+\n \n if __name__ == \"__main__\":\n     unittest.main()\ndiff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\nindex 4c0a37b..be7eab4 100644\n--- a/fortinet/tests/test_common_terminal_driver.py\n+++ b/fortinet/tests/test_common_terminal_driver.py\n@@ -9,12 +9,16 @@ from contextlib import contextmanager\n from unittest.mock import MagicMock, patch\n \n REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n sys.path.insert(0, str(REPO_ROOT))\n \n-from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n-from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n+from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n+from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n+from fortinet.common.fos_cli_driver import (  # noqa: E402\n+    FOSCliDriver,\n+    KernelPanicError,\n+)\n from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n \n \n class ByteQueueTests(unittest.TestCase):\n     def test_put_get_close_timeout_and_failure(self):\n@@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):\n         terminal._buffer_limit = 5\n         with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n             terminal._enforce_buffer_limit()\n         terminal._logger.error.assert_called_once()\n \n+    def test_timeout_preserves_partial_token_for_a_later_read(self):\n+        terminal = self.terminal_with_data(b\"Login incor\")\n+        pattern = rb\"(?m)^Login incorrect\\r?$\"\n+        index, match, output = terminal.expect([pattern], timeout=0.001)\n+        self.assertEqual((index, match), (-1, None))\n+        self.assertEqual(bytes(output), b\"Login incor\")\n+        # Inspection without discard keeps the partial token, including when\n+        # another wait expires without receiving any more bytes.\n+        _, _, output = terminal.expect([pattern], timeout=0)\n+        self.assertEqual(bytes(output), b\"Login incor\")\n+        terminal._read_queue.put(b\"rect\\n\")\n+        index, match, output = terminal.expect([pattern], timeout=0.1)\n+        self.assertEqual(index, 0)\n+        self.assertEqual(match.group(), b\"Login incorrect\")\n+        self.assertEqual(bytes(output), b\"Login incorrect\")\n+        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n+\n+    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n+        terminal = self.terminal_with_data(b\"Verifying pass\")\n+        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n+\n+        terminal._read_queue.put(b\"word...\\n\")\n+        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertIsNone(match)\n+        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n+        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n+        output.discard()\n+        self.assertEqual(bytes(terminal._buffer), b\"\")\n+\n+    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n+        prefix = b\"\\nVerifying password...\\n\"\n+        chunk = b\"admin\\nadmin\\n\"\n+        terminal = self.terminal_with_data(chunk)\n+        terminal._buffer.extend(prefix)\n+\n+        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertEqual(bytes(output), prefix + chunk)\n+        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n+        attempt.on_output(output)\n+\n+        self.assertEqual(bytes(attempt.output), prefix + chunk)\n+        self.assertEqual(bytes(terminal._buffer), b\"\")\n+        terminal._logger.warning.assert_not_called()\n+\n     def test_suppression_is_nested_and_restores_context(self):\n         @contextmanager\n         def context():\n             events.append(\"enter\")\n             try:\n@@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):\n         with self.assertRaisesRegex(OSError, \"serial failed\"):\n             queue.get(0)\n         logger.exception.assert_called_once()\n         with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n             self.assertEqual(terminal_buffer_limit_bytes(), 32)\n-        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n+        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n+            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n+        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n             with self.assertRaises(ValueError):\n                 terminal_buffer_limit_bytes()\n \n+    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n+        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n+            with self.subTest(env_name=env_name):\n+                terminal = self.terminal_with_data(b\"matched\")\n+                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n+                    terminal.expect([b\"matched\"], timeout=0.1)\n+                terminal._logger.log.assert_called_once_with(\n+                    TRACE_LEVEL,\n+                    \"buffer: bytearray(b'matched')\",\n+                )\n+\n \n class DriverTests(unittest.TestCase):\n     def make_driver(self, *, allow_recovery=False):\n         terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n         commander.ready = False\n@@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):\n         self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n         terminal.expect.return_value = (-1, None, Data(b\"\"))\n         self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n         driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n \n+    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n+        driver, _, _, logger, *_ = self.make_driver()\n+        terminal = Terminal(MagicMock(), logger)\n+        terminal._ensure_reader = lambda: None\n+        terminal._read_queue.put(b\"partial token\")\n+        driver._terminal = terminal\n+\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n+            state, output, matched = driver._next_state()\n+            self.assertEqual(state, FOSCliState.UNKNOWN)\n+            self.assertEqual(bytes(output), b\"partial token\")\n+            self.assertFalse(matched)\n+            state, output, matched = driver._next_state()\n+            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n+            self.assertEqual(bytes(output), b\"partial token\")\n+            self.assertFalse(matched)\n+\n+    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n+        driver, terminal, commander, *_ = self.make_driver()\n+        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n+        panic = (\n+            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n+            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n+        )\n+\n+        self.assertIsNone(\n+            re.search(\n+                pattern,\n+                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n+            )\n+        )\n+        match = re.search(pattern, panic)\n+        self.assertIsNotNone(match)\n+        terminal.expect.return_value = (\n+            FOSCliState.KERNEL_PANIC.value,\n+            match,\n+            Data(panic),\n+        )\n+\n+        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n+            driver.process_state()\n+\n+        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n+\n \n if __name__ == \"__main__\":\n     unittest.main()",
        "lineStart": 1198,
        "lineEnd": 2108,
        "totalLines": 2108,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716438220,
      "end": 1793716438230
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d4c4d9001o530CoMYiimwfn",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4b97a001c1OtnUD47PyDot",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 62764,
    "input": 15369,
    "output": 27,
    "reasoning": 8,
    "cache": {
      "read": 47360,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d4b97a001c1OtnUD47PyDot",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716435322,
    "completed": 1793716438236
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 62764,
    "input": 15369,
    "output": 27,
    "reasoning": 8,
    "cache": {
      "read": 47360,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 19
step-start
{
  "type": "step-start",
  "id": "prt_1a1d4ce88001cT1ciLYYlSh8yd",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4c4e1001T7bPcJXWPDQ3My"
}
Reasoning
Now I have the full diff. Interesting: the diff for test_common_stack_parsing.py shows helper `make_stack(configured, responses)` — I need to see the head version of test_common_stack_parsing.py's helpers (RecordingFeature, SerialConnection, make_stack) since other tests import from it. Let me read that file fully.

Also env.py was not in changed files but tests reference FTNT_* precedence — wait, `get_env` with aliases: terminal.py calls `get_env(BUFFER_LIMIT_ENV)` where BUFFER_LIMIT_ENV = "FOS_TERMINAL_BUFFER_LIMIT_BYTES", and the test shows FTNT_TERMINAL_BUFFER_LIMIT_BYTES works. So env.py must alias FTNT_ automatically. That's pre-existing or part of the PR? env.py isn't in changed list, so pre-existing.

Wait — but `terminal_buffer_limit_bytes` uses `get_env(BUFFER_LIMIT_ENV)` with no explicit aliases and FTNT_ variant works. So env.py has generic FTNT↔FOS aliasing. OK.

TRACE_LEVEL change: `self._logger.log(TRACE_LEVEL - 1, ...)` → `TRACE_LEVEL`. Need to check TRACE_LEVEL value in common.py. If TRACE_LEVEL = logging.DEBUG - 1 = 5, then TRACE_LEVEL - 1 = 4 was never enabled by a "TRACE" level name registration? In launch.py, addLevelName(TRACE_LEVEL_NUM, "TRACE"). If TRACE_LEVEL is 5 (DEBUG-1), then TRACE_LEVEL-1 = 4, which would only show if logger level ≤ 4 — effectively never logged. So changing to TRACE_LEVEL fixes raw serial logging at trace level. Fine.

Now the `test_idle_read_exposes_retained_prompt_newline` test change shows the behavior change: timeout Data now includes bytes retained before (the newline after the matched prompt). Feature.current_attempt.output now contains b"\n" instead of b"". This is a behavioral change in what features see as captured output — documented in the docker README. Any feature that parses captured output could now see extra leading/trailing bytes across timeouts. Since patterns search, not equality, mostly fine.

Now, remaining checks:

1. `test_common_stack_parsing.py` head — need `make_stack` signature and `RecordingFeature`.
2. features/credentials.py full head (partially seen in diff; check full file for the rest of on_session_loss and other methods).
3. common.py head — BOOTSTRAP_HOSTNAME_REGEX, PROMPT_CONTEXT_REGEX, TRACE_LEVEL, FOSCliState.
4. features/startup_config.py full head — `_startup_config_commands` and `parse_startup_config` — check correctness of the quote-continuation parser. Potential issues:
   - `_startup_config_commands` handles escaped quotes: `elif character == "\\": escaped = True` — inside a quote, a backslash escapes the next char (so `\"` inside double quotes doesn't close). But `escaped` persists across lines: if a line ends with a trailing backslash inside... `if quote is not None or escaped: pending.append(line)`. So a line ending with `\` continues to next line. Fine.
   - Edge: escaped char toggling — `for character in line: if escaped: escaped=False; elif "\\"→True; elif quote is None and char in quotes → quote = char`. Bug: if a line contains `'` then `"`... e.g. `set comment 'a"b'` — quote toggling only tracks the matching close. `'"'` handling: quote set to `'`; then `"` with quote `'` → `character == quote`? No, quote is `'`, character is `"` → not equal, and `quote is None` is False → ignored. Good.
   - But: escaped quote handling inside quote: `set comment "a\"b"` — chars: `"` opens quote; `\` sets escaped; `"` with escaped → escaped=False, ignored (doesn't close). Good.
   - Edge: backslash outside quote: `set description a\\b` (literal backslash in FortiOS?) — escaped=True, then next char consumed as escaped. If the backslash is the last char of the line, escaped=True at end → line continuation. That mimics line continuation. OK.
   - Potential issue: comment lines INSIDE a quoted string are preserved (intended). Comment lines outside quotes skipped.
   - What about `set` commands spanning lines outside quotes? The `escaped`/`pending` logic: any line ending with `\` continues. OK.
   - But one issue: `_startup_config_commands` yields logical lines that may contain newlines; then `parse_startup_config` checks `line.startswith("config ")` etc. A multi-line quoted string yields a single logical line whose start could be "config ..." — fine. But what if a quoted value's first line is a comment continuation... e.g. `set comment "#` — line doesn't start with # (starts with set). OK. What if the first physical line of a quoted continuation is inside pending (start_line tracked). Fine.
   - Hmm: within `pending`, `if not pending:` sets start_line. But `pending` is truthy check — after `pending.clear()` next iteration has empty pending. But note: `pending.append(line.rstrip())` then yield; pending.clear(). But `line.rstrip()` only strips the last line; intermediate lines keep `line.lstrip()` from when they were first added? Wait, intermediate lines are appended when `quote is not None or escaped` — at that point `line` was NOT lstripped (only lines with `not pending` get lstrip). So continuation lines keep leading whitespace. Good — README says whitespace inside quoted value is preserved.
   
   Actually wait: `if not pending:` → `line = line.lstrip()`. Continuation lines: pending non-empty → no lstrip → whitespace preserved. Then `pending.append(line.rstrip())`? No — for continuation lines: `if quote is not None or escaped: pending.append(line); continue` — appended WITHOUT rstrip? Look: code appends `line` (with trailing newline already removed via removesuffix("\n")); then `pending.append(line.rstrip())` is only in the closing path? Let me re-read:

   ```
   if quote is not None or escaped:
       pending.append(line)
       continue
   pending.append(line.rstrip())
   yield "\n".join(pending)
   pending.clear()
   ```
   Wait no, from the head file: after the quote-scanning loop:
   ```
   if quote is not None or escaped:
       pending.append(line)
       continue
   pending.append(line.rstrip())
   ```
   Hmm, the diff shows:
   ```
   +        if quote is not None or escaped:
   +            pending.append(line)
   +            continue
   +        pending.append(line.rstrip())
   +        yield "\n".join(pending)
   +        pending.clear()
   ```
   Wait that strips only the final line's trailing whitespace. But `\r` from CRLF? The file was opened in text mode default (universal newlines) so `\r\n` → `\n`. `removesuffix("\n")` handles it. But if the file uses old Mac `\r` endings... text mode converts those too. OK.

   One more: `parse_startup_config` previously stripped each line; now `_startup_config_commands` lstrips only the first line of each logical command. A `config ` line with trailing spaces would break `line.startswith("config ")`? No, startswith still works. `node = ConfigBlock(line[7:])` — trailing spaces in scope name... pre-existing concern minor.

5. Check `flatten_commands` for plain strings containing "\n" → `_flatten_quoted_lines(value.split("\n"))`. This changes behavior: previously a plain string with "\n"... wait previously `return [CommandSpec(value)]` would raise ValueError ("CLI commands must contain exactly one line"). Now strings with newlines are split into continuation commands. This enables multi-line strings in CommandSequence. But NOTE: `flatten_commands` for a string does NOT quote them (`set field "value`); only SetValue quotes. So a plain multi-line string is sent one line per continuation prompt — reasonable.

   Subtle issue with `_flatten_quoted_lines` when `validate_prompt=False`: `expected_completion_state=None` for all lines, and completion_states for multi-line: non-last lines get `(MULTILINE_PROMPT, CMD_PROMPT)`. With validate_prompt=False the completion_states still constrain which states complete the command — the command completes at either prompt. Then next line dispatched immediately at whichever state. OK.

   Edge: single-line SetValue: lines[0] = `set field "value` and then lines[-1] += '"' → `set field "value"`. Good. Multi-line: first line `set field "line1`, last line `lineN"`, continuation sends each. Matches FortiOS multiline quoted input.

   Edge: value with trailing newline: `str(self.value).strip()` removes trailing whitespace, so `"a\n"` → lines = ["a"], lines[-1] += '"' → `set field "a"` — wait `strip()` removes the newline; good.

   Edge: value like `a\n\nb` → splitlines gives ["a", "", "b"] → empty middle line sent as empty line at MULTILINE prompt. OK.

6. Now `closes_scope` on CommandSpec("exit")? `closes_scope` checks line in {"next","end"} — "exit" not included. But `exit` DOES change context (logout) — handled by `_command_may_change_context` (includes "exit"). Fine.

7. Important potential issue: `closes_scope` commands always capture output (`CommandAttempt.on_output` returns True for closes_scope) and DISCARD output from terminal buffer. `next`/`end` outputs are discarded — including any "--More--"? Unlikely on close. But the discard call: `output.discard(data)` — for matched Data (no callback), fine. For timeout Data (has callback), discard removes prefix. OK.

   But wait — there's an ordering concern in `on_state`: for CMD_PROMPT, `_complete_inflight` is called, and the failure pattern is searched in `attempt.output`. The CMD_PROMPT Data (containing the "Command fail..." lines + prompt) reaches on_output via on_state BEFORE `_complete_inflight`? In on_state: `self.on_output(output)` is called at line 292 before the inflight completion check (line ~315). Yes: on_state → on_output → inflight.on_output appends → then `_complete_inflight(state)` sees the output. Good.

   BUT: in the driver's `process_state`, for unmatched output it calls `commander.on_output(output)` first, then replaces output with empty, then `_process_state` → `commander.on_state(state, empty)`. So for UNKNOWN/TN_TIMEOUT the commander sees the bytes once. For matched CMD_PROMPT, on_state receives full Data → on_output appends → complete. Good.

   However: what about matched states that are NOT completion states of the inflight (e.g. MORE_PROMPT during a command)? on_state → on_output → captured. Fine.

8. Now a potential real defect: `_dispatch_command` when `self._active_feature and not self._in_context_reset` → on_command_dispatched → `if self._pending_feature_error is not None: return` — the command is NOT written! The inflight was created, attempt_number incremented, but terminal.write never called. Then on next prompt, `_complete_inflight` validates completion with empty output... Actually wait, `_pending_feature_error` is checked at top of on_state; recovery happens at CMD_PROMPT. So the pending error causes `_recover_feature_error` at next CMD_PROMPT → continue_after_error → skip. So the half-dispatched inflight is discarded. OK-ish. But what if the feature error is recoverable and `continue_after_error` returns None (not at command prompt)? Then `_recover_feature_error` returns False and error remains pending forever until a CMD_PROMPT. Fine.

   Actually there's a subtle case: `submit_block` is called by a feature inside `on_command_executed` (like SetLicense confirm) while a feature error is pending? `submit_block` requires `not self.busy`; busy is False. OK.

9. Now the big one I want to verify: `on_state` CMD_PROMPT sets `_recovering = False` at the top BEFORE the inflight completion check. Combined with `_dispatch_next` guard `self._recovering`. Previously (base), where was `_recovering` cleared? In base, CMD_PROMPT set `self._authenticated_once = True` only. The diff moved/added `_recovering = False` for CMD_PROMPT. This means a CMD_PROMPT observed while recovering (e.g., during the abort/replay wait) clears recovering and dispatches. That's the design for "login returns prompt without Welcome". OK.

10. Now think about `_complete_inflight` context-loss path when the completing state is CMD_PROMPT but `_prompt_context` is stale because `_extract_prompt_context` returned None for THIS prompt (mismatched hostname?). If the driver matched CMD_PROMPT with set_prompt_patterns(hostname) — the exact hostname is used, so extraction with BOOTSTRAP_HOSTNAME_REGEX also matches. But SetLicense calls `set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)` — generic. OK.

    What about `test_closing_failure_cannot_be_disabled_or_replayed`: prompts are "fw (port1) #" — the driver's CMD_PROMPT pattern requires hostname prefix... but these tests call commander.on_state directly, not through driver. Fine.

11. Another possible issue: `_extract_prompt_context` uses `matches[-1]` — last match in the Data. The Data for CMD_PROMPT includes output since last match. If the output contains multiple prompt lines (echo lines like "fw (port1) # set ip ..." and then result prompt), last one wins. But CMD_PROMPT_ECHO handles the echo case separately. For CMD_PROMPT match, the matched region ends at the prompt; Data contains everything from after previous match, which could include previous prompt echoes... Those echo lines would be matched by CLI_PROMPT_CONTEXT_PATTERN too (they end with `#`? echo lines like "fw (port1) # set ip ..." end with command text, not `#`... the regex requires `[#$][ \t]*\r?$` at line end. An echo line "fw (port1) # set ip 1.2.3.4\r\n" ends with the command, so no match. Good. But "fw (port1) #" echo followed by newline then result lines then real prompt — last match is the real prompt. Good.

12. Now check `common.py` for BOOTSTRAP_HOSTNAME_REGEX, PROMPT_CONTEXT_REGEX, TRACE_LEVEL values, and the KERNEL_PANIC pattern enum ordering: KERNEL_PANIC inserted before UNKNOWN — FOSCliState is IntEnum; adding an enum member before UNKNOWN changes UNKNOWN's value! `UNKNOWN = auto()` previously had some value, now shifted. Does anything depend on numeric values? `state.value < FOSCliState.UNKNOWN.value` in driver (line 114) — pattern states are below UNKNOWN; TN_TIMEOUT above. KERNEL_PANIC is a pattern state so must be < UNKNOWN — correct placement. Any persisted values? Probably not. Also `_next_state` returns FOSCliState(index) — index into patterns list; fine.

    Also `Data(b"")` comparisons etc. fine.

13. `launch.py` bootstrap_spin: `except KernelPanicError: self.stop(); raise` — good; panic bypasses best-effort continue. But note `handle_SIGTERM` etc. fine.

14. Driver `process_state`: `if output and not matched:` — for TN_TIMEOUT with retained buffer, `commander.on_output(output)` — commander.on_output checks `isinstance(output, Data)`; fine. But then `output = type(output)(b"")` creates a NEW Data with received_new_data defaulting to bool(b"") = False. Good — prevents on_idle_prompt path treating stale bytes as fresh? Actually on_state(TN_TIMEOUT, Data(b"")) — on_state calls on_output(Data(b"")) → returns early since falsy. Fine.

    But hmm — there's a subtle issue: `if output and not matched:` — when output is a timeout Data with retained bytes and matched is False, state = UNKNOWN if received_new_data else TN_TIMEOUT. If TN_TIMEOUT with retained bytes (no new data), commander.on_output is called with the retained buffer; if no consumer, `_inspect_output` discards only when recovering. Bytes stay. Next spin: timeout again → same Data content forwarded again to commander.on_output. If a feature later starts and captures, it gets those stale bytes prepended into attempt.output. Is that a problem? Stale bytes could contain an old "Command fail. Return code ..." line from a previous command! Consider: command A fails with "Command fail..." (captured and discarded — closed_scope/fail_on_error commands capture; plain `set` commands have capture_output? For plain commands like "get system status" without capture, on_output returns False → bytes stay in buffer!). Hmm wait: `_inspect_output` discards when `_recovering` only. So unmatched bytes for non-capturing commands accumulate in buffer until buffer limit → RuntimeError "Terminal buffer exceeded". Previously (base), timeout Data contained only `received` (fresh bytes since last expect), and the base driver forwarded them via on_output too... In base, did expect consume unmatched bytes? Base: `return -1, None, Data(bytes(received), self._discard_prefix)` — received was only the fresh bytes; buffer still retained them? Base `_discard_prefix` existed in base too (the diff shows `_discard_prefix` in base with debug log). So base behavior: expect returns fresh bytes with discard prefix authority; buffer retains. Hmm wait, if base returned only `received` (fresh bytes) with `_discard_prefix`, discarding them would remove from buffer. Who discarded in base? commander.on_output → attempt.on_output discarded if capturing. Same as now. So buffer retention behavior is same; only the VIEW changed (full buffer vs fresh bytes). The view change means:
    - Features inspecting timeout output now see previously-buffered bytes too (could double-count into attempt.output? No — attempt.on_output appends the FULL view each time and discards it; if bytes stay in buffer (no discard by any consumer) and a later timeout exposes them again and THEN an attempt is active, they're appended once. But could attempt.output get the same bytes twice? Path: timeout#1 with attempt active → appended+discarded (removed). So no. Path: timeout#1 no attempt → stays; timeout#2 attempt active → appended once, discarded. So each byte enters attempt.output at most once. Except: what if attempt is active during timeout#1 but attempt.on_output is not called because commander.on_output → inflight.on_output returns False (not capturing) and active_feature.on_output returns False → bytes retained; then command completes via matched prompt; matched Data contains those bytes too? Matched Data covers consumed bytes = everything up to match end, INCLUDING the retained bytes. So attempt.on_output (if capturing... but it wasn't capturing) — fine. If the command IS capturing: timeout#1 → appended+discarded → gone from buffer; matched Data then doesn't include them. Each byte once. 

    Now the failure-pattern check: `COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))`. Since each byte enters once, no duplication. But stale bytes from BEFORE the command was dispatched could be in the buffer when the command starts... can they enter attempt.output? Sequence: command "get status" (non-capturing) output stays in buffer; next command "end" dispatched (closes_scope, captures). Before "end"'s output arrives, a timeout exposes the buffer (retained stale "get status" output) → inflight("end").on_output appends stale bytes into attempt.output! Then when "end" completes, `_validate_completion` searches for "Command fail" in attempt.output — stale output from the PREVIOUS command could contain a failure line that was already tolerated (fail_on_error=False for the previous set command). E.g., `test_tolerated_set_failure_does_not_poison_successful_scope_close` — with capture=True, set output is captured and discarded... wait no: "set unsupported 1" has capture_output=True → attempt captures and discards immediately as output streams. So the failure text is consumed and discarded before "next" dispatch. In the capture=False case: "set unsupported 1" non-capturing → failure line "Command fail. Return code -61." stays in buffer (never consumed unless... on_state? No — those bytes arrive as part of the Data that matched CMD_PROMPT (the failure text is on the way to the prompt; matched CMD_PROMPT Data includes them; attempt.on_output for non-capturing returns False; active feature on_output False; bytes... but matched Data has no discard callback and bytes already removed from buffer by expect!). Wait — matched path: `del self._buffer[:match.end()]` — consumed bytes removed. So matched Data bytes are gone from buffer regardless. So for capture=False, the failure bytes are dropped. OK good.

    But the timeout path: retained bytes stay. Scenario: command completes with matched prompt consuming through match.end(); any bytes AFTER the match remain buffered (e.g., prompt echo of next command, "--More--" pieces). Those trailing bytes are pre-buffered when the next command starts. If the next command is closes_scope and a timeout occurs before its output, those trailing bytes enter attempt.output and get discarded. Then real failure text appended. `_validate_completion` searches attempt.output → could find a failure code in the STALE trailing bytes belonging to the previous command's output (e.g., previous "set unsupported 1" with capture=False... but those were consumed by the match as shown). Hmm, bytes after a match end: e.g., "--More--\r\n" after prompt. Could a stale "Command fail. Return code -5." line sit after the previous prompt match? The failure line appears between command echo and next prompt, so it would be BEFORE the prompt match → consumed. Unless output arrives in pieces across multiple expect calls: prompt matched early, later bytes (failure text for the NEXT... no).

    Realistic scenario: two commands back-to-back; command1's output streams but its completion prompt arrives in the same Data as command2's echo... The earliest-match rule splits. This is getting deep. The realistic risk: stale bytes in attempt.output from before the command was dispatched causing false "Command fail" detection. Actually wait — can stale bytes be present at dispatch time? After dispatch of command N, buffer contains only bytes after the last matched prompt. Those bytes belong to... they were output BEFORE command N's echo (since N's echo hasn't arrived yet). So yes, leftover fragments between prompts (e.g., asynchronous console messages, MOTD fragments, or the newline after the prompt as in `test_idle_read_exposes_retained_prompt_newline`) are in attempt.output for closes_scope commands. Could those fragments contain "Command fail. Return code X"? A failure line is printed in response to a command; if command N-1 was non-capturing (e.g., a tolerated `set` with capture_output=False)... the failure line is emitted right after command N-1's echo, before the next prompt. The prompt match consumes through the prompt; the failure line precedes the prompt → consumed → gone. So the stale content can only be bytes AFTER the last prompt, which are: prompt newline, echo of command N (but echo of N is written after dispatch; could arrive before first expect completes → part of matched/timeout data... echo lines don't contain "Command fail").

    Hmm, but there's one nasty case: FortiOS prints "Command fail. Return code -5." asynchronously? No, it's a response to a command.

    What about a session where output between prompts includes a failure from an earlier command that got split across reads: e.g., prompt P1 matched, then bytes "Command fail..." arrive (response to something? No — after P1, the next thing is command N's echo). Only async messages.

    OK, I think the stale-content risk is theoretical. Let me instead check the more concrete issue: `_restart_active_block` uses `attempt.block_index` — could be None if restart triggered from... context loss during cleanup? `_handle_context_loss` handles `self._in_cleanup` separately before calling feature. Session loss RESTART_BLOCK in cleanup? `_handle_session_loss` handles `_in_cleanup` separately (retry). So block_index None only for... `_restart_active_block` called from `_handle_context_loss` (non-cleanup, block_index set) and from session loss RESTART_BLOCK (non-cleanup). OK.

    But wait — session loss with RESTART_BLOCK when `block_index` is None: `_recovery_retries.get(None, 0)` — keyed None; harmless.

15. Now check `_handle_session_loss` non-cleanup: `self._schedule_feature_cleanup(self._active_feature, "interruption")` then calls feature.on_session_loss. If action RESTART_BLOCK → `_restart_active_block(attempt, "session lost")` → sets `_pending = deque(self._active_commands)` and `_replay_context_target = self._block_prompt_context`. But after a session loss + reconnect, the CLI is at top-level prompt. Replay starts by re-running openers — `config system interface` etc. The `_replay_context_target` = block's initial context. At top-level prompt, `_restore_replay_context` sees target == ("Interim",) vs current () → mismatch → dispatch "abort" (harmless at top level? FortiOS `abort` at top-level prompt returns an error? It would print "Command fail. Return code ..." at top level maybe — abort is suppress_output, non-capturing, completes at prompt; `_in_context_reset` path skips validation. Fine.)

16. Check `on_idle_prompt` + `_recovering` interplay: `on_idle_prompt` returns early if `self._inflight or self._recovering`. After a session loss and reconnect, `_recovering` cleared by CMD_PROMPT (on_state top) or CREDENTIAL_ACCEPTED. Fine.

17. Potential issue in `on_state`: the CMD_PROMPT branch sets `_recovering = False` unconditionally — but during recovery, `_recovering` guards `_dispatch_next` from firing mid-reconnect. If a stray CMD_PROMPT appears during recovery (e.g., login banner contains a prompt-looking line?), it would clear recovering and dispatch. That's the intended "prompt ends session recovery" behavior per comment. OK.

18. Now `_recover_feature_error` uses `self._current_state != CMD_PROMPT and not at_idle_prompt` — fine.

19. Check the scope-failure path in best-effort for cleanup: `test_cleanup_closing_failure_uses_bootstrap_error_policy` — covered.

20. Now a REAL potential bug I should scrutinize: `_complete_inflight` context-loss path calls `_handle_context_loss`, then `if self._pending_feature_error is not None: self._recover_feature_error() else: self._dispatch_next()`. But `_handle_context_loss` with RESTART_BLOCK sets `_replay_context_target`; then `_dispatch_next` → `_restore_replay_context` handles abort. Good. With FAIL → `_handle_work_error` raises or sets pending → `_recover_feature_error` skips to next feature. Good.

    But: `_dispatch_next()` is called unconditionally (line 440) even if `_recovering`? `_recovering` can't be set here. OK. And if `_in_cleanup`... `_handle_context_loss` handles in_cleanup with `_handle_work_error` which raises (fail-fast) or sets pending → `_recover_feature_error` → continue_after_error. But `_recover_feature_error` requires `self._current_state == CMD_PROMPT` — we ARE at CMD_PROMPT (state == CMD_PROMPT since context-loss only checked for CMD_PROMPT). Good.

21. Now the FAILURE ordering issue I flagged: For closes_scope commands, `attempt.output` includes streaming failure text. `_complete_inflight` checks context change BEFORE validation. A failed `next` keeps same context → validation path. But consider a `next` failure where FortiOS DOES eject to a different context (some releases?) — then context-loss path takes priority: feature.on_context_loss → default for `next`: `next` has session_loss default RESTART_BLOCK → context_loss RESTART_BLOCK → restart block. Hmm, but `closes_scope` failure is documented as "always fatal... even when fail_on_error=False" and "cannot be replayed". If the failed `next` also ejects context, the code replays the block instead of failing! The test `test_closing_failure_cannot_be_disabled_or_replayed` only covers same-context? No wait — it prompts with "interface" context AFTER the failure: `self.prompt(commander, "interface")` — before=port1... let me trace: initial `self.prompt(commander, "port1")` sets context ("port1",)... wait the RecordingFeature block is CommandSequence("commit", [CommandSpec("next"...), "set must-not-run 1"]). Dispatch "next" with prompt_context_before=("port1",). Then output chunks (failure text) via commander.on_output — no state. Then `self.prompt(commander, "interface")`: on_state(CMD_PROMPT, ...) → on_output (inflight none... wait inflight still active) → attempt captures → `_complete_inflight(CMD_PROMPT)` → prompt_context_after = ("interface",) → `_prompt_context_changed`: before ("port1",) != ("interface",) → `_command_may_change_context("next")` → True → NOT context loss. So falls to `_validate_completion` → failure detected. 

    So because `next`/`end` are in `_command_may_change_context`, any context change after them is attributed to the legitimate scope close, and validation still runs. So the ordering concern is actually resolved: the context-loss check exempts scope-closers. The only hole: a scope-closer command whose context change was NOT caused by itself (e.g., someone else's logout mid-command) → treated as legit → failure check still runs (since validation happens after context-change exemption... wait no: if `_prompt_context_changed` returns False because `_command_may_change_context` is True, flow continues to `_validate_completion` — yes, validation runs. Good: closes_scope failure is always checked.

    What about context loss for non-scope commands where the after-context is the SAME as before (no change) — no issue.

    What about context loss where before is None (never extracted, e.g., first prompt of the session at a nested scope)? `_prompt_context_changed` returns False → no context-loss detection → command "completes" in wrong scope. When is before None? `_prompt_context` starts None; first CMD_PROMPT sets it via extraction (or keeps None if extraction fails). submit_block captures `_block_prompt_context = self._prompt_context`. First prompt of a session is top-level in practice. Edge acceptable.

22. Now check `test_common_stack_parsing.py` head for `make_stack(configured, responses)` helper used by new tests, and RecordingFeature import in admin tests. Let me read the head file.

23. Also verify `features/credentials.py` full head (post-diff) and `features/startup_config.py` full head around parse_startup_config.

24. Also the README claims. docker README documents the new behavior well. fortigate README documents quoted strings. Check README statement "An unexpected prompt follows the bootstrap error policy" — matches `_flatten_quoted_lines` with validate_prompt; unexpected prompt raises → bootstrap policy. OK.

25. One more potential defect: `flatten_commands` splitting plain strings on "\n" — but `ConfigBlock`/`EditBlock` open_line can't contain \n. `CommandSequence` children strings with \n now split. Any feature passing a string with "\n" that previously would have raised ValueError at CommandSpec creation (fail-fast) now silently sends multi-line? That's the intended feature.

    But subtle: `_flatten_quoted_lines` with `fail_on_error=False` default — plain multi-line strings get fail_on_error=False, whereas a single-line string gets fail_on_error=False too (CommandSpec default). Consistent.

    Edge: a string with trailing "\n": `"set alias x\n"` → split → ["set alias x", ""] → two commands: last line is empty string → CommandSpec("") — writes empty line "\r" at MULTILINE prompt. Previously ValueError. Behavior change but reasonable.

    Also `_flatten_quoted_lines` for single line: completion_states=() (len(lines)>1 false), expected=CMD_PROMPT, continuation=False. Good.

    One more: SetValue with value containing "\r"? `str(self.value).strip()` keeps "\r" if embedded mid-string? "\r" in line → CommandSpec raises ValueError "must contain exactly one line". Value with "\r\n" → splitlines handles. OK.

26. `test_common_stack_boundaries.py` changes: `initial_prompt` param. `state_case` sets `initial_prompt=b"fw (global) #"` for CMD_PROMPT_ECHO. Fine.

27. Check `common.py` head for BOOTSTRAP_HOSTNAME_REGEX/PROMPT_CONTEXT_REGEX definitions and TRACE_LEVEL value; and check `features/credentials.py` full.

Let me read: test_common_stack_parsing.py (head), features/credentials.py (head full), common.py (head), features/startup_config.py (head).
The diff is fully mapped. Now let me read the remaining head files that new tests depend on: `test_common_stack_parsing.py` helpers, `features/credentials.py`, `common.py`, and `features/startup_config.py`.
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_stack_parsing.py"
}

Output

<path>/source/head/fortinet/tests/test_common_stack_parsing.py</path>
<type>file</type>
<content>
1: """End-to-end parsing from a serial connection through the FortiOS commander."""
2: 
3: import queue
4: import sys
5: import unittest
6: from pathlib import Path
7: from unittest.mock import MagicMock
8: 
9: REPO_ROOT = Path(__file__).resolve().parents[2]
10: sys.path.insert(0, str(REPO_ROOT))
11: 
12: from fortinet.common.cli_commands import (  # noqa: E402
13:     CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,
14: )
15: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
16: from fortinet.common.features.base import Feature  # noqa: E402
17: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
18: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
19: from fortinet.common.terminal import Terminal  # noqa: E402
20: 
21: 
22: class SerialConnection:
23:     """A serial-like connection that answers each write with a byte stream."""
24: 
25:     def __init__(self, responses):
26:         self._incoming = queue.Queue()
27:         self._responses = responses
28:         self.writes = []
29:         self.closed = False
30:         self._incoming.put(b"fw login:\r\n")
31: 
32:     def read_very_eager(self):
33:         try:
34:             return self._incoming.get_nowait()
35:         except queue.Empty:
36:             return b""
37: 
38:     def write(self, data):
39:         data = bytes(data)
40:         self.writes.append(data)
41:         response = self._responses.get(data)
42:         if callable(response):
43:             response = response()
44:         if response:
45:             chunks = response if isinstance(response, (tuple, list)) else (response,)
46:             for chunk in chunks:
47:                 if chunk:
48:                     self._incoming.put(bytes(chunk))
49: 
50:     def close(self):
51:         self.closed = True
52: 
53:     def suppress_output(self):
54:         from contextlib import nullcontext
55:         return nullcontext()
56: 
57: 
58: class RecordingFeature(Feature):
59:     def __init__(self, commander, name, commands):
60:         super().__init__(None, commander, name)
61:         self.commands = commands
62:         self.executed = []
63:         self.dispatched = []
64: 
65:     def activate(self):
66:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))
67: 
68:     def on_command_dispatched(self, attempt):
69:         super().on_command_dispatched(attempt)
70:         self.dispatched.append(attempt)
71: 
72:     def on_command_executed(self, attempt, state):
73:         self.executed.append((attempt.spec.line, bytes(attempt.output), state))
74: 
75: 
76: class FullStackParsingTests(unittest.TestCase):
77:     def make_stack(self, features, responses, *, allow_credential_recovery=False):
78:         logger = MagicMock()
79:         connection = SerialConnection(responses)
80:         terminal = Terminal(connection, logger, default_wait="fw #")
81:         commander = FOSCommander(terminal, logger)
82:         commander.start(features(commander))
83:         driver = FOSCliDriver(
84:             terminal=terminal,
85:             commander=commander,
86:             credentials=Credentials("admin", "secret"),
87:             logger=logger,
88:             bootstrap_password="Bootstrap1!",
89:             activate_blank_credentials=MagicMock(),
90:             activate_bootstrap_credentials=MagicMock(),
91:             allow_credential_recovery=allow_credential_recovery,
92:         )
93:         return connection, terminal, commander, driver
94: 
95:     def test_login_command_echo_multiline_output_and_continuation(self):
96:         result = b"".join([
97:             b"fw # show full-configuration system dns\r\n",
98:             b"config system dns\r\n",
99:             b"    set protocol dot\r\n",
100:             b"    set primary 9.9.9.9\r\n",
101:             b"end\r\n",
102:             b"fw #\r\n",
103:         ])
104:         responses = {
105:             b"admin\r": b"Password:",
106:             b"secret\r": b"Welcome!\r\nfw #\r\n",
107:             b"show full-configuration system dns\r": result,
108:             b'set comment "first line\r': b">\r\n",
109:             b"second line\r": b">\r\n",
110:             b'third line"\r': b"fw #\r\n",
111:         }
112:         features = []
113: 
114:         def configured(commander):
115:             inspect = RecordingFeature(commander, "inspect", [
116:                 CommandSpec("show full-configuration system dns", capture_output=True),
117:             ])
118:             multiline = RecordingFeature(commander, "multiline", [
119:                 SetValue("comment", "first line\nsecond line\nthird line"),
120:             ])
121:             features.extend([inspect, multiline])
122:             return features
123: 
124:         connection, terminal, commander, driver = self.make_stack(configured, responses)
125:         driver.process_state()
126: 
127:         self.assertTrue(commander.ready)
128:         self.assertTrue(commander.startup_complete)
129:         self.assertTrue(all(feature.completed for feature in features))
130:         self.assertTrue(connection.closed)
131:         self.assertEqual(connection.writes, [
132:             b"admin\r",
133:             b"secret\r",
134:             b"show full-configuration system dns\r",
135:             b'set comment "first line\r',
136:             b"second line\r",
137:             b'third line"\r',
138:         ])
139:         self.assertEqual(len(features[0].executed), 1)
140:         captured = features[0].executed[0][1]
141:         self.assertIn(b"set protocol dot", captured)
142:         self.assertIn(b"set primary 9.9.9.9", captured)
143:         self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)
144:         self.assertEqual(
145:             [entry[2] for entry in features[1].executed],
146:             [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],
147:         )
148:         self.assertTrue(all(attempt.output for attempt in features[1].dispatched))
149:         self.assertEqual(bytes(terminal._buffer), b"")
150: 
151:     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):
152:         responses = {
153:             b"admin\r": b"Password:",
154:             b"secret\r": b"Welcome!\r\nfw (global) #\r\n",
155:             b"get system status\r": (
156:                 b"fw (global) # get system status\r\n"
157:                 b"Version: FortiGate-VM64 v7.4.2,build2571\r\n"
158:                 b"--More--\r\n"
159:                 b"Serial-Number: FGVMTEST\r\n"
160:                 b"fw (global) #\r\n"
161:             ),
162:             b" \r": b"fw (global) #\r\n",
163:         }
164:         feature_ref = []
165: 
166:         class PagerFeature(RecordingFeature):
167:             def on_command_executed(self, attempt, state):
168:                 super().on_command_executed(attempt, state)
169:                 self.commander.feature_complete(self)
170: 
171:         def configured(commander):
172:             feature = PagerFeature(commander, "status", [
173:                 CommandSpec("get system status", capture_output=True),
174:             ])
175:             feature_ref.append(feature)
176:             return [feature]
177: 
178:         connection, _terminal, commander, driver = self.make_stack(configured, responses)
179:         driver.process_state()
180: 
181:         feature = feature_ref[0]
182:         self.assertTrue(commander.ready)
183:         self.assertTrue(feature.completed)
184:         self.assertEqual(connection.writes, [
185:             b"admin\r", b"secret\r", b"get system status\r", b" ",
186:         ])
187:         captured = feature.executed[0][1]
188:         self.assertIn(b"FortiGate-VM64 v7.4.2,build2571", captured)
189:         self.assertIn(b"Serial-Number: FGVMTEST", captured)
190:         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)
191:         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)
192: 
193:     def test_aborted_interface_edit_recovers_through_serial_driver(self):
194:         ip_responses = iter([
195:             b"abort\r\nfw (Interim)#\r\n",
196:             b"fw (port1) (Interim)#\r\n",
197:         ])
198:         responses = {
199:             b"admin\r": b"Password:",
200:             b"secret\r": b"Welcome!\r\nfw (Interim)#\r\n",
201:             b"config system interface\r": b"fw (interface) (Interim)#\r\n",
202:             b"edit port1\r": b"fw (port1) (Interim)#\r\n",
203:             b"set ip 10.0.52.4/24\r": lambda: next(ip_responses),
204:             b"set allowaccess ping https ssh http\r": b"fw (port1) (Interim)#\r\n",
205:             b"next\r": b"fw (interface) (Interim)#\r\n",
206:             b"end\r": b"fw (Interim)#\r\n",
207:         }
208:         feature_ref = []
209: 
210:         def configured(commander):
211:             feature = RecordingFeature(commander, "management", [
212:                 ConfigBlock("system interface", [EditBlock("port1", [
213:                     "set ip 10.0.52.4/24", "set allowaccess ping https ssh http",
214:                 ])]),
215:             ])
216:             feature_ref.append(feature)
217:             return [feature]
218: 
219:         connection, terminal, commander, driver = self.make_stack(configured, responses)
220:         try:
221:             driver.process_state()
222:             self.assertTrue(commander.ready)
223:             self.assertTrue(feature_ref[0].completed)
224:             self.assertEqual(connection.writes, [
225:                 b"admin\r", b"secret\r",
226:                 b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
227:                 b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
228:                 b"set allowaccess ping https ssh http\r", b"next\r", b"end\r",
229:             ])
230:         finally:
231:             terminal.close()
232: 
233:     def test_failed_next_ejects_before_end_through_serial_driver(self):
234:         responses = {
235:             b"admin\r": b"Password:",
236:             b"secret\r": b"Welcome!\r\nfw #\r\n",
237:             b"config system interface\r": b"fw (interface)#\r\n",
238:             b"edit port1\r": b"fw (port1)#\r\n",
239:             b"set unsupported 1\r": b"Command fail. Return code -61.\r\nfw (port1)#\r\n",
240:             b"next\r": (
241:                 b"Command fa", b"il. Return code -5.\r\nfw (port1)#\r\n",
242:             ),
243:         }
244:         feature_ref = []
245: 
246:         def configured(commander):
247:             feature = RecordingFeature(commander, "management", [
248:                 ConfigBlock("system interface", [EditBlock("port1", ["set unsupported 1"])]),
249:             ])
250:             feature_ref.append(feature)
251:             return [feature]
252: 
253:         connection, terminal, commander, driver = self.make_stack(configured, responses)
254:         try:
255:             with self.assertRaisesRegex(RuntimeError, "'next'.*return code -5"):
256:                 driver.process_state()
257:             self.assertEqual(connection.writes, [
258:                 b"admin\r", b"secret\r", b"config system interface\r",
259:                 b"edit port1\r", b"set unsupported 1\r", b"next\r",
260:             ])
261:             self.assertFalse(feature_ref[0].completed)
262:             self.assertFalse(commander.ready)
263:         finally:
264:             terminal.close()
265: 
266: 
267: if __name__ == "__main__":
268:     unittest.main()

(End of file - total 268 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d5d66c001bFnVXOBZI4H6PN",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4c4e1001T7bPcJXWPDQ3My",
  "callID": "call_40bfee0bff3e41b6ad621a67",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_stack_parsing.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_stack_parsing.py</path>\n<type>file</type>\n<content>\n1: \"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n2: \n3: import queue\n4: import sys\n5: import unittest\n6: from pathlib import Path\n7: from unittest.mock import MagicMock\n8: \n9: REPO_ROOT = Path(__file__).resolve().parents[2]\n10: sys.path.insert(0, str(REPO_ROOT))\n11: \n12: from fortinet.common.cli_commands import (  # noqa: E402\n13:     CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n14: )\n15: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n16: from fortinet.common.features.base import Feature  # noqa: E402\n17: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n18: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n19: from fortinet.common.terminal import Terminal  # noqa: E402\n20: \n21: \n22: class SerialConnection:\n23:     \"\"\"A serial-like connection that answers each write with a byte stream.\"\"\"\n24: \n25:     def __init__(self, responses):\n26:         self._incoming = queue.Queue()\n27:         self._responses = responses\n28:         self.writes = []\n29:         self.closed = False\n30:         self._incoming.put(b\"fw login:\\r\\n\")\n31: \n32:     def read_very_eager(self):\n33:         try:\n34:             return self._incoming.get_nowait()\n35:         except queue.Empty:\n36:             return b\"\"\n37: \n38:     def write(self, data):\n39:         data = bytes(data)\n40:         self.writes.append(data)\n41:         response = self._responses.get(data)\n42:         if callable(response):\n43:             response = response()\n44:         if response:\n45:             chunks = response if isinstance(response, (tuple, list)) else (response,)\n46:             for chunk in chunks:\n47:                 if chunk:\n48:                     self._incoming.put(bytes(chunk))\n49: \n50:     def close(self):\n51:         self.closed = True\n52: \n53:     def suppress_output(self):\n54:         from contextlib import nullcontext\n55:         return nullcontext()\n56: \n57: \n58: class RecordingFeature(Feature):\n59:     def __init__(self, commander, name, commands):\n60:         super().__init__(None, commander, name)\n61:         self.commands = commands\n62:         self.executed = []\n63:         self.dispatched = []\n64: \n65:     def activate(self):\n66:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n67: \n68:     def on_command_dispatched(self, attempt):\n69:         super().on_command_dispatched(attempt)\n70:         self.dispatched.append(attempt)\n71: \n72:     def on_command_executed(self, attempt, state):\n73:         self.executed.append((attempt.spec.line, bytes(attempt.output), state))\n74: \n75: \n76: class FullStackParsingTests(unittest.TestCase):\n77:     def make_stack(self, features, responses, *, allow_credential_recovery=False):\n78:         logger = MagicMock()\n79:         connection = SerialConnection(responses)\n80:         terminal = Terminal(connection, logger, default_wait=\"fw #\")\n81:         commander = FOSCommander(terminal, logger)\n82:         commander.start(features(commander))\n83:         driver = FOSCliDriver(\n84:             terminal=terminal,\n85:             commander=commander,\n86:             credentials=Credentials(\"admin\", \"secret\"),\n87:             logger=logger,\n88:             bootstrap_password=\"Bootstrap1!\",\n89:             activate_blank_credentials=MagicMock(),\n90:             activate_bootstrap_credentials=MagicMock(),\n91:             allow_credential_recovery=allow_credential_recovery,\n92:         )\n93:         return connection, terminal, commander, driver\n94: \n95:     def test_login_command_echo_multiline_output_and_continuation(self):\n96:         result = b\"\".join([\n97:             b\"fw # show full-configuration system dns\\r\\n\",\n98:             b\"config system dns\\r\\n\",\n99:             b\"    set protocol dot\\r\\n\",\n100:             b\"    set primary 9.9.9.9\\r\\n\",\n101:             b\"end\\r\\n\",\n102:             b\"fw #\\r\\n\",\n103:         ])\n104:         responses = {\n105:             b\"admin\\r\": b\"Password:\",\n106:             b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n107:             b\"show full-configuration system dns\\r\": result,\n108:             b'set comment \"first line\\r': b\">\\r\\n\",\n109:             b\"second line\\r\": b\">\\r\\n\",\n110:             b'third line\"\\r': b\"fw #\\r\\n\",\n111:         }\n112:         features = []\n113: \n114:         def configured(commander):\n115:             inspect = RecordingFeature(commander, \"inspect\", [\n116:                 CommandSpec(\"show full-configuration system dns\", capture_output=True),\n117:             ])\n118:             multiline = RecordingFeature(commander, \"multiline\", [\n119:                 SetValue(\"comment\", \"first line\\nsecond line\\nthird line\"),\n120:             ])\n121:             features.extend([inspect, multiline])\n122:             return features\n123: \n124:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n125:         driver.process_state()\n126: \n127:         self.assertTrue(commander.ready)\n128:         self.assertTrue(commander.startup_complete)\n129:         self.assertTrue(all(feature.completed for feature in features))\n130:         self.assertTrue(connection.closed)\n131:         self.assertEqual(connection.writes, [\n132:             b\"admin\\r\",\n133:             b\"secret\\r\",\n134:             b\"show full-configuration system dns\\r\",\n135:             b'set comment \"first line\\r',\n136:             b\"second line\\r\",\n137:             b'third line\"\\r',\n138:         ])\n139:         self.assertEqual(len(features[0].executed), 1)\n140:         captured = features[0].executed[0][1]\n141:         self.assertIn(b\"set protocol dot\", captured)\n142:         self.assertIn(b\"set primary 9.9.9.9\", captured)\n143:         self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)\n144:         self.assertEqual(\n145:             [entry[2] for entry in features[1].executed],\n146:             [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],\n147:         )\n148:         self.assertTrue(all(attempt.output for attempt in features[1].dispatched))\n149:         self.assertEqual(bytes(terminal._buffer), b\"\")\n150: \n151:     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n152:         responses = {\n153:             b\"admin\\r\": b\"Password:\",\n154:             b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n155:             b\"get system status\\r\": (\n156:                 b\"fw (global) # get system status\\r\\n\"\n157:                 b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n158:                 b\"--More--\\r\\n\"\n159:                 b\"Serial-Number: FGVMTEST\\r\\n\"\n160:                 b\"fw (global) #\\r\\n\"\n161:             ),\n162:             b\" \\r\": b\"fw (global) #\\r\\n\",\n163:         }\n164:         feature_ref = []\n165: \n166:         class PagerFeature(RecordingFeature):\n167:             def on_command_executed(self, attempt, state):\n168:                 super().on_command_executed(attempt, state)\n169:                 self.commander.feature_complete(self)\n170: \n171:         def configured(commander):\n172:             feature = PagerFeature(commander, \"status\", [\n173:                 CommandSpec(\"get system status\", capture_output=True),\n174:             ])\n175:             feature_ref.append(feature)\n176:             return [feature]\n177: \n178:         connection, _terminal, commander, driver = self.make_stack(configured, responses)\n179:         driver.process_state()\n180: \n181:         feature = feature_ref[0]\n182:         self.assertTrue(commander.ready)\n183:         self.assertTrue(feature.completed)\n184:         self.assertEqual(connection.writes, [\n185:             b\"admin\\r\", b\"secret\\r\", b\"get system status\\r\", b\" \",\n186:         ])\n187:         captured = feature.executed[0][1]\n188:         self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n189:         self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n190:         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n191:         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n192: \n193:     def test_aborted_interface_edit_recovers_through_serial_driver(self):\n194:         ip_responses = iter([\n195:             b\"abort\\r\\nfw (Interim)#\\r\\n\",\n196:             b\"fw (port1) (Interim)#\\r\\n\",\n197:         ])\n198:         responses = {\n199:             b\"admin\\r\": b\"Password:\",\n200:             b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n201:             b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n202:             b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n203:             b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n204:             b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n205:             b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n206:             b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n207:         }\n208:         feature_ref = []\n209: \n210:         def configured(commander):\n211:             feature = RecordingFeature(commander, \"management\", [\n212:                 ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n213:                     \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n214:                 ])]),\n215:             ])\n216:             feature_ref.append(feature)\n217:             return [feature]\n218: \n219:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n220:         try:\n221:             driver.process_state()\n222:             self.assertTrue(commander.ready)\n223:             self.assertTrue(feature_ref[0].completed)\n224:             self.assertEqual(connection.writes, [\n225:                 b\"admin\\r\", b\"secret\\r\",\n226:                 b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n227:                 b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n228:                 b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n229:             ])\n230:         finally:\n231:             terminal.close()\n232: \n233:     def test_failed_next_ejects_before_end_through_serial_driver(self):\n234:         responses = {\n235:             b\"admin\\r\": b\"Password:\",\n236:             b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n237:             b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n238:             b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n239:             b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n240:             b\"next\\r\": (\n241:                 b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n242:             ),\n243:         }\n244:         feature_ref = []\n245: \n246:         def configured(commander):\n247:             feature = RecordingFeature(commander, \"management\", [\n248:                 ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n249:             ])\n250:             feature_ref.append(feature)\n251:             return [feature]\n252: \n253:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n254:         try:\n255:             with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n256:                 driver.process_state()\n257:             self.assertEqual(connection.writes, [\n258:                 b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n259:                 b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n260:             ])\n261:             self.assertFalse(feature_ref[0].completed)\n262:             self.assertFalse(commander.ready)\n263:         finally:\n264:             terminal.close()\n265: \n266: \n267: if __name__ == \"__main__\":\n268:     unittest.main()\n\n(End of file - total 268 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_stack_parsing.py",
    "metadata": {
      "preview": "\"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n\nimport queue\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n)\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_stack_parsing.py",
        "text": "\"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n\nimport queue\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n)\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\n\n\nclass SerialConnection:\n    \"\"\"A serial-like connection that answers each write with a byte stream.\"\"\"\n\n    def __init__(self, responses):\n        self._incoming = queue.Queue()\n        self._responses = responses\n        self.writes = []\n        self.closed = False\n        self._incoming.put(b\"fw login:\\r\\n\")\n\n    def read_very_eager(self):\n        try:\n            return self._incoming.get_nowait()\n        except queue.Empty:\n            return b\"\"\n\n    def write(self, data):\n        data = bytes(data)\n        self.writes.append(data)\n        response = self._responses.get(data)\n        if callable(response):\n            response = response()\n        if response:\n            chunks = response if isinstance(response, (tuple, list)) else (response,)\n            for chunk in chunks:\n                if chunk:\n                    self._incoming.put(bytes(chunk))\n\n    def close(self):\n        self.closed = True\n\n    def suppress_output(self):\n        from contextlib import nullcontext\n        return nullcontext()\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):\n        super().__init__(None, commander, name)\n        self.commands = commands\n        self.executed = []\n        self.dispatched = []\n\n    def activate(self):\n        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n\n    def on_command_dispatched(self, attempt):\n        super().on_command_dispatched(attempt)\n        self.dispatched.append(attempt)\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append((attempt.spec.line, bytes(attempt.output), state))\n\n\nclass FullStackParsingTests(unittest.TestCase):\n    def make_stack(self, features, responses, *, allow_credential_recovery=False):\n        logger = MagicMock()\n        connection = SerialConnection(responses)\n        terminal = Terminal(connection, logger, default_wait=\"fw #\")\n        commander = FOSCommander(terminal, logger)\n        commander.start(features(commander))\n        driver = FOSCliDriver(\n            terminal=terminal,\n            commander=commander,\n            credentials=Credentials(\"admin\", \"secret\"),\n            logger=logger,\n            bootstrap_password=\"Bootstrap1!\",\n            activate_blank_credentials=MagicMock(),\n            activate_bootstrap_credentials=MagicMock(),\n            allow_credential_recovery=allow_credential_recovery,\n        )\n        return connection, terminal, commander, driver\n\n    def test_login_command_echo_multiline_output_and_continuation(self):\n        result = b\"\".join([\n            b\"fw # show full-configuration system dns\\r\\n\",\n            b\"config system dns\\r\\n\",\n            b\"    set protocol dot\\r\\n\",\n            b\"    set primary 9.9.9.9\\r\\n\",\n            b\"end\\r\\n\",\n            b\"fw #\\r\\n\",\n        ])\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n            b\"show full-configuration system dns\\r\": result,\n            b'set comment \"first line\\r': b\">\\r\\n\",\n            b\"second line\\r\": b\">\\r\\n\",\n            b'third line\"\\r': b\"fw #\\r\\n\",\n        }\n        features = []\n\n        def configured(commander):\n            inspect = RecordingFeature(commander, \"inspect\", [\n                CommandSpec(\"show full-configuration system dns\", capture_output=True),\n            ])\n            multiline = RecordingFeature(commander, \"multiline\", [\n                SetValue(\"comment\", \"first line\\nsecond line\\nthird line\"),\n            ])\n            features.extend([inspect, multiline])\n            return features\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        driver.process_state()\n\n        self.assertTrue(commander.ready)\n        self.assertTrue(commander.startup_complete)\n        self.assertTrue(all(feature.completed for feature in features))\n        self.assertTrue(connection.closed)\n        self.assertEqual(connection.writes, [\n            b\"admin\\r\",\n            b\"secret\\r\",\n            b\"show full-configuration system dns\\r\",\n            b'set comment \"first line\\r',\n            b\"second line\\r\",\n            b'third line\"\\r',\n        ])\n        self.assertEqual(len(features[0].executed), 1)\n        captured = features[0].executed[0][1]\n        self.assertIn(b\"set protocol dot\", captured)\n        self.assertIn(b\"set primary 9.9.9.9\", captured)\n        self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)\n        self.assertEqual(\n            [entry[2] for entry in features[1].executed],\n            [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],\n        )\n        self.assertTrue(all(attempt.output for attempt in features[1].dispatched))\n        self.assertEqual(bytes(terminal._buffer), b\"\")\n\n    def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n            b\"get system status\\r\": (\n                b\"fw (global) # get system status\\r\\n\"\n                b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n                b\"--More--\\r\\n\"\n                b\"Serial-Number: FGVMTEST\\r\\n\"\n                b\"fw (global) #\\r\\n\"\n            ),\n            b\" \\r\": b\"fw (global) #\\r\\n\",\n        }\n        feature_ref = []\n\n        class PagerFeature(RecordingFeature):\n            def on_command_executed(self, attempt, state):\n                super().on_command_executed(attempt, state)\n                self.commander.feature_complete(self)\n\n        def configured(commander):\n            feature = PagerFeature(commander, \"status\", [\n                CommandSpec(\"get system status\", capture_output=True),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, _terminal, commander, driver = self.make_stack(configured, responses)\n        driver.process_state()\n\n        feature = feature_ref[0]\n        self.assertTrue(commander.ready)\n        self.assertTrue(feature.completed)\n        self.assertEqual(connection.writes, [\n            b\"admin\\r\", b\"secret\\r\", b\"get system status\\r\", b\" \",\n        ])\n        captured = feature.executed[0][1]\n        self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n        self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n        self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n        self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n\n    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n        ip_responses = iter([\n            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n            b\"fw (port1) (Interim)#\\r\\n\",\n        ])\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n        }\n        feature_ref = []\n\n        def configured(commander):\n            feature = RecordingFeature(commander, \"management\", [\n                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n                ])]),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        try:\n            driver.process_state()\n            self.assertTrue(commander.ready)\n            self.assertTrue(feature_ref[0].completed)\n            self.assertEqual(connection.writes, [\n                b\"admin\\r\", b\"secret\\r\",\n                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n            ])\n        finally:\n            terminal.close()\n\n    def test_failed_next_ejects_before_end_through_serial_driver(self):\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n            b\"next\\r\": (\n                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n            ),\n        }\n        feature_ref = []\n\n        def configured(commander):\n            feature = RecordingFeature(commander, \"management\", [\n                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        try:\n            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n                driver.process_state()\n            self.assertEqual(connection.writes, [\n                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n            ])\n            self.assertFalse(feature_ref[0].completed)\n            self.assertFalse(commander.ready)\n        finally:\n            terminal.close()\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 268,
        "totalLines": 268,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716508272,
      "end": 1793716508279
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/credentials.py"
}

Output

<path>/source/head/fortinet/common/features/credentials.py</path>
<type>file</type>
<content>
1: """Administrator bootstrap feature."""
2: 
3: from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction
4: from ..common import FOSCliState
5: 
6: from .base import StaticFeature
7: 
8: 
9: class CredentialsFeature(StaticFeature):
10:     """Configure the administrator, then log out and authenticate again."""
11: 
12:     def __init__(self, vm, commander):
13:         self._activate_after_admin_commit = False
14:         self._desired_credentials_activated = False
15:         self._password_change_committed = False
16:         credentials = vm.desired_credentials
17:         admin_children = ["set accprofile super_admin"]
18:         if credentials.password:
19:             admin_children.append(CommandSpec(
20:                 f"set password {credentials.password}",
21:                 session_loss=SessionLossAction.CONTINUE,
22:                 capture_output=True,
23:                 fail_on_error=True,
24:             ))
25:         elif credentials.username == "admin":
26:             admin_children.append(CommandSpec(
27:                 "unset password", session_loss=SessionLossAction.CONTINUE,
28:                 capture_output=True,
29:                 fail_on_error=True,
30:             ))
31:         super().__init__(vm, commander, "admin", [
32:             ConfigBlock("system password-policy", ["set status disable"]),
33:             ConfigBlock("system admin", [EditBlock(credentials.username, admin_children)]),
34:             CommandSequence("admin-relogin", [CommandSpec(
35:                 "exit",
36:                 session_loss=SessionLossAction.CONTINUE,
37:                 capture_output=True,
38:                 fail_on_error=True,
39:                 # A successful logout takes the session-loss path. Returning
40:                 # straight to a CLI prompt must not count as verification.
41:                 expected_completion_state=FOSCliState.PROVIDE_USERNAME,
42:             )]),
43:         ], on_complete=lambda: self._activate_desired_credentials())
44: 
45:     def on_command_dispatched(self, attempt):
46:         if attempt.spec.line == "exit":
47:             self._activate_desired_credentials()
48:         super().on_command_dispatched(attempt)
49: 
50:     def on_session_loss(self, attempt):
51:         if attempt.spec.line == "exit":
52:             # The commander resumes this block only at the authenticated CLI
53:             # prompt. Clear the logout command so it cannot be replayed.
54:             return SessionLossAction.CONTINUE
55:         if self._is_password_command(attempt.spec.line):
56:             self._activate_desired_credentials()
57:             self._activate_after_admin_commit = False
58:             return SessionLossAction.CONTINUE
59:         if self._activate_after_admin_commit and attempt.spec.line == "next":
60:             # Some releases log out during the commit instead of returning
61:             # its CLI prompt. Authenticate with the committed password.
62:             self._activate_desired_credentials()
63:             self._activate_after_admin_commit = False
64:             self._password_change_committed = True
65:             return SessionLossAction.CONTINUE
66:         if self._password_change_committed:
67:             # FortiOS may log out as the admin edit closes. The password
68:             # command and `next` have already committed the new credentials,
69:             # so replaying this block would use the previous password again.
70:             return SessionLossAction.CONTINUE
71:         return super().on_session_loss(attempt)
72: 
73:     def on_command_executed(self, command, state):
74:         line = command.spec.line
75:         if self._is_password_command(line):
76:             self._activate_after_admin_commit = True
77:         elif self._activate_after_admin_commit and line == "next":
78:             self._activate_desired_credentials()
79:             self._activate_after_admin_commit = False
80:             self._password_change_committed = True
81: 
82:     @staticmethod
83:     def _is_password_command(line):
84:         return line.startswith("set password ") or line == "unset password"
85: 
86:     def _activate_desired_credentials(self):
87:         if self._desired_credentials_activated:
88:             return
89:         self.vm.activate_desired_credentials()
90:         self._desired_credentials_activated = True

(End of file - total 90 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d5d6ac001Ek7ShT5Zg9e67m",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4c4e1001T7bPcJXWPDQ3My",
  "callID": "call_b15322c1ecb44ab092a5c037",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/credentials.py"
    },
    "output": "<path>/source/head/fortinet/common/features/credentials.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Administrator bootstrap feature.\"\"\"\n2: \n3: from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n4: from ..common import FOSCliState\n5: \n6: from .base import StaticFeature\n7: \n8: \n9: class CredentialsFeature(StaticFeature):\n10:     \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n11: \n12:     def __init__(self, vm, commander):\n13:         self._activate_after_admin_commit = False\n14:         self._desired_credentials_activated = False\n15:         self._password_change_committed = False\n16:         credentials = vm.desired_credentials\n17:         admin_children = [\"set accprofile super_admin\"]\n18:         if credentials.password:\n19:             admin_children.append(CommandSpec(\n20:                 f\"set password {credentials.password}\",\n21:                 session_loss=SessionLossAction.CONTINUE,\n22:                 capture_output=True,\n23:                 fail_on_error=True,\n24:             ))\n25:         elif credentials.username == \"admin\":\n26:             admin_children.append(CommandSpec(\n27:                 \"unset password\", session_loss=SessionLossAction.CONTINUE,\n28:                 capture_output=True,\n29:                 fail_on_error=True,\n30:             ))\n31:         super().__init__(vm, commander, \"admin\", [\n32:             ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n33:             ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n34:             CommandSequence(\"admin-relogin\", [CommandSpec(\n35:                 \"exit\",\n36:                 session_loss=SessionLossAction.CONTINUE,\n37:                 capture_output=True,\n38:                 fail_on_error=True,\n39:                 # A successful logout takes the session-loss path. Returning\n40:                 # straight to a CLI prompt must not count as verification.\n41:                 expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n42:             )]),\n43:         ], on_complete=lambda: self._activate_desired_credentials())\n44: \n45:     def on_command_dispatched(self, attempt):\n46:         if attempt.spec.line == \"exit\":\n47:             self._activate_desired_credentials()\n48:         super().on_command_dispatched(attempt)\n49: \n50:     def on_session_loss(self, attempt):\n51:         if attempt.spec.line == \"exit\":\n52:             # The commander resumes this block only at the authenticated CLI\n53:             # prompt. Clear the logout command so it cannot be replayed.\n54:             return SessionLossAction.CONTINUE\n55:         if self._is_password_command(attempt.spec.line):\n56:             self._activate_desired_credentials()\n57:             self._activate_after_admin_commit = False\n58:             return SessionLossAction.CONTINUE\n59:         if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n60:             # Some releases log out during the commit instead of returning\n61:             # its CLI prompt. Authenticate with the committed password.\n62:             self._activate_desired_credentials()\n63:             self._activate_after_admin_commit = False\n64:             self._password_change_committed = True\n65:             return SessionLossAction.CONTINUE\n66:         if self._password_change_committed:\n67:             # FortiOS may log out as the admin edit closes. The password\n68:             # command and `next` have already committed the new credentials,\n69:             # so replaying this block would use the previous password again.\n70:             return SessionLossAction.CONTINUE\n71:         return super().on_session_loss(attempt)\n72: \n73:     def on_command_executed(self, command, state):\n74:         line = command.spec.line\n75:         if self._is_password_command(line):\n76:             self._activate_after_admin_commit = True\n77:         elif self._activate_after_admin_commit and line == \"next\":\n78:             self._activate_desired_credentials()\n79:             self._activate_after_admin_commit = False\n80:             self._password_change_committed = True\n81: \n82:     @staticmethod\n83:     def _is_password_command(line):\n84:         return line.startswith(\"set password \") or line == \"unset password\"\n85: \n86:     def _activate_desired_credentials(self):\n87:         if self._desired_credentials_activated:\n88:             return\n89:         self.vm.activate_desired_credentials()\n90:         self._desired_credentials_activated = True\n\n(End of file - total 90 lines)\n</content>",
    "title": "source/head/fortinet/common/features/credentials.py",
    "metadata": {
      "preview": "\"\"\"Administrator bootstrap feature.\"\"\"\n\nfrom ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\nfrom ..common import FOSCliState\n\nfrom .base import StaticFeature\n\n\nclass CredentialsFeature(StaticFeature):\n    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n\n    def __init__(self, vm, commander):\n        self._activate_after_admin_commit = False\n        self._desired_credentials_activated = False\n        self._password_change_committed = False\n        credentials = vm.desired_credentials\n        admin_children = [\"set accprofile super_admin\"]\n        if credentials.password:\n            admin_children.append(CommandSpec(\n                f\"set password {credentials.password}\",",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/credentials.py",
        "text": "\"\"\"Administrator bootstrap feature.\"\"\"\n\nfrom ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\nfrom ..common import FOSCliState\n\nfrom .base import StaticFeature\n\n\nclass CredentialsFeature(StaticFeature):\n    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n\n    def __init__(self, vm, commander):\n        self._activate_after_admin_commit = False\n        self._desired_credentials_activated = False\n        self._password_change_committed = False\n        credentials = vm.desired_credentials\n        admin_children = [\"set accprofile super_admin\"]\n        if credentials.password:\n            admin_children.append(CommandSpec(\n                f\"set password {credentials.password}\",\n                session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n            ))\n        elif credentials.username == \"admin\":\n            admin_children.append(CommandSpec(\n                \"unset password\", session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n            ))\n        super().__init__(vm, commander, \"admin\", [\n            ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n            ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n            CommandSequence(\"admin-relogin\", [CommandSpec(\n                \"exit\",\n                session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n                # A successful logout takes the session-loss path. Returning\n                # straight to a CLI prompt must not count as verification.\n                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n            )]),\n        ], on_complete=lambda: self._activate_desired_credentials())\n\n    def on_command_dispatched(self, attempt):\n        if attempt.spec.line == \"exit\":\n            self._activate_desired_credentials()\n        super().on_command_dispatched(attempt)\n\n    def on_session_loss(self, attempt):\n        if attempt.spec.line == \"exit\":\n            # The commander resumes this block only at the authenticated CLI\n            # prompt. Clear the logout command so it cannot be replayed.\n            return SessionLossAction.CONTINUE\n        if self._is_password_command(attempt.spec.line):\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            return SessionLossAction.CONTINUE\n        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n            # Some releases log out during the commit instead of returning\n            # its CLI prompt. Authenticate with the committed password.\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            self._password_change_committed = True\n            return SessionLossAction.CONTINUE\n        if self._password_change_committed:\n            # FortiOS may log out as the admin edit closes. The password\n            # command and `next` have already committed the new credentials,\n            # so replaying this block would use the previous password again.\n            return SessionLossAction.CONTINUE\n        return super().on_session_loss(attempt)\n\n    def on_command_executed(self, command, state):\n        line = command.spec.line\n        if self._is_password_command(line):\n            self._activate_after_admin_commit = True\n        elif self._activate_after_admin_commit and line == \"next\":\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            self._password_change_committed = True\n\n    @staticmethod\n    def _is_password_command(line):\n        return line.startswith(\"set password \") or line == \"unset password\"\n\n    def _activate_desired_credentials(self):\n        if self._desired_credentials_activated:\n            return\n        self.vm.activate_desired_credentials()\n        self._desired_credentials_activated = True",
        "lineStart": 1,
        "lineEnd": 90,
        "totalLines": 90,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716508336,
      "end": 1793716508342
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/common.py",
  "limit": 120
}

Output

<path>/source/head/fortinet/common/common.py</path>
<type>file</type>
<content>
1: from enum import IntEnum, auto
2: from functools import wraps
3: from time import perf_counter
4: 
5: 
6: TRACE_LEVEL = 9
7: 
8: 
9: class FOSCliState(IntEnum):
10:     PROVIDE_USERNAME = 0
11:     PROVIDE_PASSWORD = auto()
12:     CHANGE_PASSWORD = auto()
13:     CREDENTIAL_REJECTED = auto()
14:     CREDENTIAL_ACCEPTED = auto()
15:     LIC_FAIL = auto()
16:     CMD_PROMPT = auto()
17:     CMD_PROMPT_ECHO = auto()
18:     SHUTTING_DOWN = auto()
19:     REBOOTING = auto()
20:     SESSION_LOST = auto()
21:     CURRENT_PASSWORD = auto()
22:     CONFIRMATION = auto()
23:     CHANGE_PASSWORD_CONFIRM = auto()
24:     MORE_PROMPT = auto()
25:     MULTILINE_PROMPT = auto()
26:     KERNEL_PANIC = auto()
27:     UNKNOWN = auto()  # Non-patterns from here on.
28:     TN_TIMEOUT = auto()
29: 
30: 
31: GENERIC_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+"
32: DEFAULT_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+(?:-VM64)?-KVM(?:-[A-Za-z0-9]*)?"
33: LICENSED_HOSTNAME_REGEX = rb"[A-Z][A-Z0-9]{7,}"
34: BOOTSTRAP_HOSTNAME_REGEX = (
35:     rb"(?:" + GENERIC_HOSTNAME_REGEX + rb"|" + DEFAULT_HOSTNAME_REGEX + rb"|" + LICENSED_HOSTNAME_REGEX + rb")"
36: )
37: PROMPT_CONTEXT_REGEX = rb"(?:[ \t]+\([^)]+\))*"
38: DEFAULT_HOSTNAME_PROMPT = rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*\r?$"
39: DEFAULT_HOSTNAME_PROMPT_ECHO = rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*[^\r\n]+(?:\r?\n)?"
40: 
41: FOS_CLI_STATE_PATTERNS = [None] * FOSCliState.UNKNOWN.value
42: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_USERNAME.value] = (
43:         rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX +
44:         rb"(?:\((?:Primary|Secondary)\))?"
45:         rb"[ \t]+login:[ \t]*"
46: )
47: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD.value] = rb"(?m)^New Password:[ \t]*"
48: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_PASSWORD.value] = rb"(?m)^Password:[ \t]*"
49: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_REJECTED.value] = rb"(?m)^Login incorrect\r?$"
50: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_ACCEPTED.value] = rb"(?m)^Welcome ?!\r?$"
51: FOS_CLI_STATE_PATTERNS[FOSCliState.LIC_FAIL.value] = rb"(?mi)^VM license install failed\.?\r?$"
52: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT.value] = DEFAULT_HOSTNAME_PROMPT
53: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT_ECHO.value] = DEFAULT_HOSTNAME_PROMPT_ECHO
54: FOS_CLI_STATE_PATTERNS[FOSCliState.SHUTTING_DOWN.value] = b"system is going down"
55: FOS_CLI_STATE_PATTERNS[FOSCliState.REBOOTING.value] = b"stand by while rebooting"
56: FOS_CLI_STATE_PATTERNS[FOSCliState.SESSION_LOST.value] = (
57:     rb"\*ATTENTION\*: Admin sessions removed because license registration status changed.*"
58: )
59: FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (
60:     rb"(?mi)(?:Please enter current administrator password|Current Password):?\s*"
61: )
62: FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb"(?mi)Do you want to continue\?"
63: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb"(?mi)^Confirm Password:[ \t]*"
64: FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb"--More--\s*"
65: FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb"(?m)^>[ \t]*\r?$"
66: FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (
67:     rb"(?mi)^Kernel panic(?: - not syncing)?:[^\r\n]*\r?\n"
68:     rb"CPU: [0-9]+ PID: [0-9]+ Comm: [^\r\n]+"
69: )
70: 
71: DEF_POLICY_COMPLIANT_PASSWORD = "FortinetFOS1!"
72: DEFAULT_USERNAME = "admin"
73: DEFAULT_PASSWORD = DEFAULT_USERNAME
74: 
75: 
76: class Credentials:
77:     def __init__(self, username, password) -> None:
78:         super().__init__()
79:         self.username = username
80:         self.password = password
81: 
82: 
83: def timed(fn):
84:     @wraps(fn)
85:     def wrapper(*args, **kwargs):
86:         started = perf_counter()
87:         try:
88:             return fn(*args, **kwargs)
89:         finally:
90:             print(f"{fn.__qualname__}: {perf_counter() - started:.3f}s")
91: 
92:     return wrapper

(End of file - total 92 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d5d6ee001mSZTuUVraXtnm4",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4c4e1001T7bPcJXWPDQ3My",
  "callID": "call_fd08d2413634424c81610ed3",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/common.py",
      "limit": 120
    },
    "output": "<path>/source/head/fortinet/common/common.py</path>\n<type>file</type>\n<content>\n1: from enum import IntEnum, auto\n2: from functools import wraps\n3: from time import perf_counter\n4: \n5: \n6: TRACE_LEVEL = 9\n7: \n8: \n9: class FOSCliState(IntEnum):\n10:     PROVIDE_USERNAME = 0\n11:     PROVIDE_PASSWORD = auto()\n12:     CHANGE_PASSWORD = auto()\n13:     CREDENTIAL_REJECTED = auto()\n14:     CREDENTIAL_ACCEPTED = auto()\n15:     LIC_FAIL = auto()\n16:     CMD_PROMPT = auto()\n17:     CMD_PROMPT_ECHO = auto()\n18:     SHUTTING_DOWN = auto()\n19:     REBOOTING = auto()\n20:     SESSION_LOST = auto()\n21:     CURRENT_PASSWORD = auto()\n22:     CONFIRMATION = auto()\n23:     CHANGE_PASSWORD_CONFIRM = auto()\n24:     MORE_PROMPT = auto()\n25:     MULTILINE_PROMPT = auto()\n26:     KERNEL_PANIC = auto()\n27:     UNKNOWN = auto()  # Non-patterns from here on.\n28:     TN_TIMEOUT = auto()\n29: \n30: \n31: GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n32: DEFAULT_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+(?:-VM64)?-KVM(?:-[A-Za-z0-9]*)?\"\n33: LICENSED_HOSTNAME_REGEX = rb\"[A-Z][A-Z0-9]{7,}\"\n34: BOOTSTRAP_HOSTNAME_REGEX = (\n35:     rb\"(?:\" + GENERIC_HOSTNAME_REGEX + rb\"|\" + DEFAULT_HOSTNAME_REGEX + rb\"|\" + LICENSED_HOSTNAME_REGEX + rb\")\"\n36: )\n37: PROMPT_CONTEXT_REGEX = rb\"(?:[ \\t]+\\([^)]+\\))*\"\n38: DEFAULT_HOSTNAME_PROMPT = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n39: DEFAULT_HOSTNAME_PROMPT_ECHO = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n40: \n41: FOS_CLI_STATE_PATTERNS = [None] * FOSCliState.UNKNOWN.value\n42: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_USERNAME.value] = (\n43:         rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX +\n44:         rb\"(?:\\((?:Primary|Secondary)\\))?\"\n45:         rb\"[ \\t]+login:[ \\t]*\"\n46: )\n47: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD.value] = rb\"(?m)^New Password:[ \\t]*\"\n48: FOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_PASSWORD.value] = rb\"(?m)^Password:[ \\t]*\"\n49: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_REJECTED.value] = rb\"(?m)^Login incorrect\\r?$\"\n50: FOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_ACCEPTED.value] = rb\"(?m)^Welcome ?!\\r?$\"\n51: FOS_CLI_STATE_PATTERNS[FOSCliState.LIC_FAIL.value] = rb\"(?mi)^VM license install failed\\.?\\r?$\"\n52: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT.value] = DEFAULT_HOSTNAME_PROMPT\n53: FOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT_ECHO.value] = DEFAULT_HOSTNAME_PROMPT_ECHO\n54: FOS_CLI_STATE_PATTERNS[FOSCliState.SHUTTING_DOWN.value] = b\"system is going down\"\n55: FOS_CLI_STATE_PATTERNS[FOSCliState.REBOOTING.value] = b\"stand by while rebooting\"\n56: FOS_CLI_STATE_PATTERNS[FOSCliState.SESSION_LOST.value] = (\n57:     rb\"\\*ATTENTION\\*: Admin sessions removed because license registration status changed.*\"\n58: )\n59: FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n60:     rb\"(?mi)(?:Please enter current administrator password|Current Password):?\\s*\"\n61: )\n62: FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n63: FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n64: FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n65: FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n66: FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n67:     rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n68:     rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n69: )\n70: \n71: DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n72: DEFAULT_USERNAME = \"admin\"\n73: DEFAULT_PASSWORD = DEFAULT_USERNAME\n74: \n75: \n76: class Credentials:\n77:     def __init__(self, username, password) -> None:\n78:         super().__init__()\n79:         self.username = username\n80:         self.password = password\n81: \n82: \n83: def timed(fn):\n84:     @wraps(fn)\n85:     def wrapper(*args, **kwargs):\n86:         started = perf_counter()\n87:         try:\n88:             return fn(*args, **kwargs)\n89:         finally:\n90:             print(f\"{fn.__qualname__}: {perf_counter() - started:.3f}s\")\n91: \n92:     return wrapper\n\n(End of file - total 92 lines)\n</content>",
    "title": "source/head/fortinet/common/common.py",
    "metadata": {
      "preview": "from enum import IntEnum, auto\nfrom functools import wraps\nfrom time import perf_counter\n\n\nTRACE_LEVEL = 9\n\n\nclass FOSCliState(IntEnum):\n    PROVIDE_USERNAME = 0\n    PROVIDE_PASSWORD = auto()\n    CHANGE_PASSWORD = auto()\n    CREDENTIAL_REJECTED = auto()\n    CREDENTIAL_ACCEPTED = auto()\n    LIC_FAIL = auto()\n    CMD_PROMPT = auto()\n    CMD_PROMPT_ECHO = auto()\n    SHUTTING_DOWN = auto()\n    REBOOTING = auto()\n    SESSION_LOST = auto()",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/common.py",
        "text": "from enum import IntEnum, auto\nfrom functools import wraps\nfrom time import perf_counter\n\n\nTRACE_LEVEL = 9\n\n\nclass FOSCliState(IntEnum):\n    PROVIDE_USERNAME = 0\n    PROVIDE_PASSWORD = auto()\n    CHANGE_PASSWORD = auto()\n    CREDENTIAL_REJECTED = auto()\n    CREDENTIAL_ACCEPTED = auto()\n    LIC_FAIL = auto()\n    CMD_PROMPT = auto()\n    CMD_PROMPT_ECHO = auto()\n    SHUTTING_DOWN = auto()\n    REBOOTING = auto()\n    SESSION_LOST = auto()\n    CURRENT_PASSWORD = auto()\n    CONFIRMATION = auto()\n    CHANGE_PASSWORD_CONFIRM = auto()\n    MORE_PROMPT = auto()\n    MULTILINE_PROMPT = auto()\n    KERNEL_PANIC = auto()\n    UNKNOWN = auto()  # Non-patterns from here on.\n    TN_TIMEOUT = auto()\n\n\nGENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\nDEFAULT_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+(?:-VM64)?-KVM(?:-[A-Za-z0-9]*)?\"\nLICENSED_HOSTNAME_REGEX = rb\"[A-Z][A-Z0-9]{7,}\"\nBOOTSTRAP_HOSTNAME_REGEX = (\n    rb\"(?:\" + GENERIC_HOSTNAME_REGEX + rb\"|\" + DEFAULT_HOSTNAME_REGEX + rb\"|\" + LICENSED_HOSTNAME_REGEX + rb\")\"\n)\nPROMPT_CONTEXT_REGEX = rb\"(?:[ \\t]+\\([^)]+\\))*\"\nDEFAULT_HOSTNAME_PROMPT = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\nDEFAULT_HOSTNAME_PROMPT_ECHO = rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n\nFOS_CLI_STATE_PATTERNS = [None] * FOSCliState.UNKNOWN.value\nFOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_USERNAME.value] = (\n        rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX +\n        rb\"(?:\\((?:Primary|Secondary)\\))?\"\n        rb\"[ \\t]+login:[ \\t]*\"\n)\nFOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD.value] = rb\"(?m)^New Password:[ \\t]*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.PROVIDE_PASSWORD.value] = rb\"(?m)^Password:[ \\t]*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_REJECTED.value] = rb\"(?m)^Login incorrect\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CREDENTIAL_ACCEPTED.value] = rb\"(?m)^Welcome ?!\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.LIC_FAIL.value] = rb\"(?mi)^VM license install failed\\.?\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT.value] = DEFAULT_HOSTNAME_PROMPT\nFOS_CLI_STATE_PATTERNS[FOSCliState.CMD_PROMPT_ECHO.value] = DEFAULT_HOSTNAME_PROMPT_ECHO\nFOS_CLI_STATE_PATTERNS[FOSCliState.SHUTTING_DOWN.value] = b\"system is going down\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.REBOOTING.value] = b\"stand by while rebooting\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.SESSION_LOST.value] = (\n    rb\"\\*ATTENTION\\*: Admin sessions removed because license registration status changed.*\"\n)\nFOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n    rb\"(?mi)(?:Please enter current administrator password|Current Password):?\\s*\"\n)\nFOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\nFOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n)\n\nDEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\nDEFAULT_USERNAME = \"admin\"\nDEFAULT_PASSWORD = DEFAULT_USERNAME\n\n\nclass Credentials:\n    def __init__(self, username, password) -> None:\n        super().__init__()\n        self.username = username\n        self.password = password\n\n\ndef timed(fn):\n    @wraps(fn)\n    def wrapper(*args, **kwargs):\n        started = perf_counter()\n        try:\n            return fn(*args, **kwargs)\n        finally:\n            print(f\"{fn.__qualname__}: {perf_counter() - started:.3f}s\")\n\n    return wrapper",
        "lineStart": 1,
        "lineEnd": 92,
        "totalLines": 92,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716508403,
      "end": 1793716508410
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d5d6fd001c9W4Q17gUjTdzu",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d4c4e1001T7bPcJXWPDQ3My",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 82827,
    "input": 12878,
    "output": 109,
    "reasoning": 7120,
    "cache": {
      "read": 62720,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d4c4e1001T7bPcJXWPDQ3My",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716438241,
    "completed": 1793716508417
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 82827,
    "input": 12878,
    "output": 109,
    "reasoning": 7120,
    "cache": {
      "read": 62720,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 20
step-start
{
  "type": "step-start",
  "id": "prt_1a1d5ed43001AHhzVWC9y4EEy5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5d708001LvU45UtGXR2UuB"
}
Reasoning
Now let me check `features/startup_config.py` head fully and the diff for `test_common_stack_boundaries.py` (I have it). Also, need to check `features/credentials.py` — one potential issue in `on_command_dispatched`: it calls `self._activate_desired_credentials()` when "exit" is dispatched — BEFORE the exit command is sent. So the driver's active credentials become the desired password, but the session is still logged in as the old admin (old password still valid for the current session; FortiOS sessions keep working after changing your own password? Usually the admin session survives password change). But the "exit" command completes at PROVIDE_USERNAME (login). Since credentials are switched to desired before sending exit, the login prompt is answered with the desired credentials. Good.

But wait — there's a wrinkle: the "exit" spec has `expected_completion_state=FOSCliState.PROVIDE_USERNAME`. `_validate_completion` raises "CLI command completed at unexpected prompt: expected PROVIDE_USERNAME, received CMD_PROMPT" — the test `test_logout_must_return_to_login` asserts "expected PROVIDE_USERNAME" message. Good.

But now the context-loss check in `_complete_inflight`: for "exit", `_command_may_change_context("exit")` → True → exempt from context loss. Fine.

Another wrinkle: `_command_may_change_context` includes "exit" — but for the `exit` in admin-relogin, session loss CONTINUE is used when the logout actually happens (SESSION_LOST state). Good.

Now `on_session_loss` for "exit" returns CONTINUE → `_pending.clear()` → the exit command is not replayed; then reconnect → prompt → `_dispatch_next` → pending empty → on_block_complete → StaticFeature._submit_next → no more blocks → on_complete → `_activate_desired_credentials()` (idempotent) → feature_complete. Good.

Now startup_config.py head: let me read it.
Now let me read the full head of `features/startup_config.py` to verify the new quote-continuation parser, and check `env.py` for the aliasing used by the terminal tests.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/startup_config.py"
}

Output

<path>/source/head/fortinet/common/features/startup_config.py</path>
<type>file</type>
<content>
1: """User startup configuration feature."""
2: 
3: import os
4: 
5: from ..cli_commands import ConfigBlock, EditBlock
6: from ..env import has_env
7: from .base import StaticFeature
8: 
9: 
10: class ApplyStartupConfig(StaticFeature):
11:     def __init__(self, vm, commander):
12:         path = "/config/startup-config.cfg"
13:         blocks = parse_startup_config(path) if os.path.exists(path) else []
14:         blocks = filter_startup_config_blocks(blocks, commander.logger)
15:         super().__init__(vm, commander, "startup-config", blocks)
16: 
17: 
18: def filter_startup_config_blocks(blocks, logger):
19:     """Skip startup DNS configuration that conflicts with FortiGuard hook DNS."""
20:     if not (
21:         has_env("FOS_FORTIGUARD_HOOKS")
22:         and (
23:             has_env("FOS_MGMT_DNS_PRIMARY", aliases=("FTNT_DNS_PRIMARY",))
24:             or has_env(
25:                 "FOS_MGMT_DNS_SECONDARY",
26:                 aliases=("FTNT_DNS_SECONDARY",),
27:                 legacy_aliases=("FTNT_MGMG_DNS_SECONDARY", "FOS_MGMG_DNS_SECONDARY"),
28:             )
29:             or has_env("FTNT_DNS_PROTOCOL")
30:         )
31:     ):
32:         return blocks
33: 
34:     filtered = [
35:         block
36:         for block in blocks
37:         if not (isinstance(block, ConfigBlock) and block.value == "system dns")
38:     ]
39:     if len(filtered) != len(blocks):
40:         logger.warning(
41:             "Skipping startup config block 'config system dns' because "
42:             "FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY, "
43:             "FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL"
44:         )
45:     return filtered
46: 
47: 
48: def _startup_config_commands(config):
49:     """Yield logical CLI commands while retaining quoted newlines verbatim."""
50:     pending = []
51:     quote = None
52:     start_line = None
53:     for number, raw_line in enumerate(config, start=1):
54:         # Text mode normalizes file line endings. Only remove the delimiter;
55:         # whitespace and comment/scope-looking lines inside quotes are data.
56:         line = raw_line.removesuffix("\n")
57:         if not pending:
58:             line = line.lstrip()
59:             if not line or line.startswith("#"):
60:                 continue
61:             start_line = number
62: 
63:         escaped = False
64:         for character in line:
65:             if escaped:
66:                 escaped = False
67:             elif character == "\\":
68:                 escaped = True
69:             elif character == quote:
70:                 quote = None
71:             elif quote is None and character in {"'", '"'}:
72:                 quote = character
73: 
74:         if quote is not None or escaped:
75:             pending.append(line)
76:             continue
77:         pending.append(line.rstrip())
78:         yield "\n".join(pending)
79:         pending.clear()
80: 
81:     if pending:
82:         reason = "unterminated quoted string" if quote else "unfinished line continuation"
83:         raise ValueError(
84:             f"Startup config malformed. {reason} starting on line {start_line}."
85:         )
86: 
87: 
88: def parse_startup_config(path):
89:     roots = []
90:     stack = []
91:     with open(path) as config:
92:         for line in _startup_config_commands(config):
93:             if line.startswith("config "):
94:                 node = ConfigBlock(line[7:])
95:                 (stack[-1].children if stack else roots).append(node)
96:                 stack.append(node)
97:             elif line.startswith("edit "):
98:                 node = EditBlock(line[5:])
99:                 if not stack:
100:                     raise ValueError("Startup config malformed. edit outside config scope.")
101:                 stack[-1].children.append(node)
102:                 stack.append(node)
103:             elif line == "next":
104:                 if not stack or not isinstance(stack[-1], EditBlock):
105:                     raise ValueError("Startup config malformed. next outside edit scope.")
106:                 stack.pop()
107:             elif line == "end":
108:                 if not stack or not isinstance(stack[-1], ConfigBlock):
109:                     raise ValueError("Startup config malformed. end outside config scope.")
110:                 stack.pop()
111:             else:
112:                 if not stack:
113:                     raise ValueError("Startup config malformed. command outside config scope.")
114:                 stack[-1].children.append(line)
115:     if stack:
116:         raise ValueError("Startup config malformed. unmatched config or edit scope.")
117:     return roots

(End of file - total 117 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d5fa1a001JXuwuXaiPPQq3S",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5d708001LvU45UtGXR2UuB",
  "callID": "call_c66863b76db64d30bdd30e2e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/startup_config.py"
    },
    "output": "<path>/source/head/fortinet/common/features/startup_config.py</path>\n<type>file</type>\n<content>\n1: \"\"\"User startup configuration feature.\"\"\"\n2: \n3: import os\n4: \n5: from ..cli_commands import ConfigBlock, EditBlock\n6: from ..env import has_env\n7: from .base import StaticFeature\n8: \n9: \n10: class ApplyStartupConfig(StaticFeature):\n11:     def __init__(self, vm, commander):\n12:         path = \"/config/startup-config.cfg\"\n13:         blocks = parse_startup_config(path) if os.path.exists(path) else []\n14:         blocks = filter_startup_config_blocks(blocks, commander.logger)\n15:         super().__init__(vm, commander, \"startup-config\", blocks)\n16: \n17: \n18: def filter_startup_config_blocks(blocks, logger):\n19:     \"\"\"Skip startup DNS configuration that conflicts with FortiGuard hook DNS.\"\"\"\n20:     if not (\n21:         has_env(\"FOS_FORTIGUARD_HOOKS\")\n22:         and (\n23:             has_env(\"FOS_MGMT_DNS_PRIMARY\", aliases=(\"FTNT_DNS_PRIMARY\",))\n24:             or has_env(\n25:                 \"FOS_MGMT_DNS_SECONDARY\",\n26:                 aliases=(\"FTNT_DNS_SECONDARY\",),\n27:                 legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n28:             )\n29:             or has_env(\"FTNT_DNS_PROTOCOL\")\n30:         )\n31:     ):\n32:         return blocks\n33: \n34:     filtered = [\n35:         block\n36:         for block in blocks\n37:         if not (isinstance(block, ConfigBlock) and block.value == \"system dns\")\n38:     ]\n39:     if len(filtered) != len(blocks):\n40:         logger.warning(\n41:             \"Skipping startup config block 'config system dns' because \"\n42:             \"FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY, \"\n43:             \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n44:         )\n45:     return filtered\n46: \n47: \n48: def _startup_config_commands(config):\n49:     \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n50:     pending = []\n51:     quote = None\n52:     start_line = None\n53:     for number, raw_line in enumerate(config, start=1):\n54:         # Text mode normalizes file line endings. Only remove the delimiter;\n55:         # whitespace and comment/scope-looking lines inside quotes are data.\n56:         line = raw_line.removesuffix(\"\\n\")\n57:         if not pending:\n58:             line = line.lstrip()\n59:             if not line or line.startswith(\"#\"):\n60:                 continue\n61:             start_line = number\n62: \n63:         escaped = False\n64:         for character in line:\n65:             if escaped:\n66:                 escaped = False\n67:             elif character == \"\\\\\":\n68:                 escaped = True\n69:             elif character == quote:\n70:                 quote = None\n71:             elif quote is None and character in {\"'\", '\"'}:\n72:                 quote = character\n73: \n74:         if quote is not None or escaped:\n75:             pending.append(line)\n76:             continue\n77:         pending.append(line.rstrip())\n78:         yield \"\\n\".join(pending)\n79:         pending.clear()\n80: \n81:     if pending:\n82:         reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n83:         raise ValueError(\n84:             f\"Startup config malformed. {reason} starting on line {start_line}.\"\n85:         )\n86: \n87: \n88: def parse_startup_config(path):\n89:     roots = []\n90:     stack = []\n91:     with open(path) as config:\n92:         for line in _startup_config_commands(config):\n93:             if line.startswith(\"config \"):\n94:                 node = ConfigBlock(line[7:])\n95:                 (stack[-1].children if stack else roots).append(node)\n96:                 stack.append(node)\n97:             elif line.startswith(\"edit \"):\n98:                 node = EditBlock(line[5:])\n99:                 if not stack:\n100:                     raise ValueError(\"Startup config malformed. edit outside config scope.\")\n101:                 stack[-1].children.append(node)\n102:                 stack.append(node)\n103:             elif line == \"next\":\n104:                 if not stack or not isinstance(stack[-1], EditBlock):\n105:                     raise ValueError(\"Startup config malformed. next outside edit scope.\")\n106:                 stack.pop()\n107:             elif line == \"end\":\n108:                 if not stack or not isinstance(stack[-1], ConfigBlock):\n109:                     raise ValueError(\"Startup config malformed. end outside config scope.\")\n110:                 stack.pop()\n111:             else:\n112:                 if not stack:\n113:                     raise ValueError(\"Startup config malformed. command outside config scope.\")\n114:                 stack[-1].children.append(line)\n115:     if stack:\n116:         raise ValueError(\"Startup config malformed. unmatched config or edit scope.\")\n117:     return roots\n\n(End of file - total 117 lines)\n</content>",
    "title": "source/head/fortinet/common/features/startup_config.py",
    "metadata": {
      "preview": "\"\"\"User startup configuration feature.\"\"\"\n\nimport os\n\nfrom ..cli_commands import ConfigBlock, EditBlock\nfrom ..env import has_env\nfrom .base import StaticFeature\n\n\nclass ApplyStartupConfig(StaticFeature):\n    def __init__(self, vm, commander):\n        path = \"/config/startup-config.cfg\"\n        blocks = parse_startup_config(path) if os.path.exists(path) else []\n        blocks = filter_startup_config_blocks(blocks, commander.logger)\n        super().__init__(vm, commander, \"startup-config\", blocks)\n\n\ndef filter_startup_config_blocks(blocks, logger):\n    \"\"\"Skip startup DNS configuration that conflicts with FortiGuard hook DNS.\"\"\"\n    if not (",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/startup_config.py",
        "text": "\"\"\"User startup configuration feature.\"\"\"\n\nimport os\n\nfrom ..cli_commands import ConfigBlock, EditBlock\nfrom ..env import has_env\nfrom .base import StaticFeature\n\n\nclass ApplyStartupConfig(StaticFeature):\n    def __init__(self, vm, commander):\n        path = \"/config/startup-config.cfg\"\n        blocks = parse_startup_config(path) if os.path.exists(path) else []\n        blocks = filter_startup_config_blocks(blocks, commander.logger)\n        super().__init__(vm, commander, \"startup-config\", blocks)\n\n\ndef filter_startup_config_blocks(blocks, logger):\n    \"\"\"Skip startup DNS configuration that conflicts with FortiGuard hook DNS.\"\"\"\n    if not (\n        has_env(\"FOS_FORTIGUARD_HOOKS\")\n        and (\n            has_env(\"FOS_MGMT_DNS_PRIMARY\", aliases=(\"FTNT_DNS_PRIMARY\",))\n            or has_env(\n                \"FOS_MGMT_DNS_SECONDARY\",\n                aliases=(\"FTNT_DNS_SECONDARY\",),\n                legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n            )\n            or has_env(\"FTNT_DNS_PROTOCOL\")\n        )\n    ):\n        return blocks\n\n    filtered = [\n        block\n        for block in blocks\n        if not (isinstance(block, ConfigBlock) and block.value == \"system dns\")\n    ]\n    if len(filtered) != len(blocks):\n        logger.warning(\n            \"Skipping startup config block 'config system dns' because \"\n            \"FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY, \"\n            \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n        )\n    return filtered\n\n\ndef _startup_config_commands(config):\n    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n    pending = []\n    quote = None\n    start_line = None\n    for number, raw_line in enumerate(config, start=1):\n        # Text mode normalizes file line endings. Only remove the delimiter;\n        # whitespace and comment/scope-looking lines inside quotes are data.\n        line = raw_line.removesuffix(\"\\n\")\n        if not pending:\n            line = line.lstrip()\n            if not line or line.startswith(\"#\"):\n                continue\n            start_line = number\n\n        escaped = False\n        for character in line:\n            if escaped:\n                escaped = False\n            elif character == \"\\\\\":\n                escaped = True\n            elif character == quote:\n                quote = None\n            elif quote is None and character in {\"'\", '\"'}:\n                quote = character\n\n        if quote is not None or escaped:\n            pending.append(line)\n            continue\n        pending.append(line.rstrip())\n        yield \"\\n\".join(pending)\n        pending.clear()\n\n    if pending:\n        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n        raise ValueError(\n            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n        )\n\n\ndef parse_startup_config(path):\n    roots = []\n    stack = []\n    with open(path) as config:\n        for line in _startup_config_commands(config):\n            if line.startswith(\"config \"):\n                node = ConfigBlock(line[7:])\n                (stack[-1].children if stack else roots).append(node)\n                stack.append(node)\n            elif line.startswith(\"edit \"):\n                node = EditBlock(line[5:])\n                if not stack:\n                    raise ValueError(\"Startup config malformed. edit outside config scope.\")\n                stack[-1].children.append(node)\n                stack.append(node)\n            elif line == \"next\":\n                if not stack or not isinstance(stack[-1], EditBlock):\n                    raise ValueError(\"Startup config malformed. next outside edit scope.\")\n                stack.pop()\n            elif line == \"end\":\n                if not stack or not isinstance(stack[-1], ConfigBlock):\n                    raise ValueError(\"Startup config malformed. end outside config scope.\")\n                stack.pop()\n            else:\n                if not stack:\n                    raise ValueError(\"Startup config malformed. command outside config scope.\")\n                stack[-1].children.append(line)\n    if stack:\n        raise ValueError(\"Startup config malformed. unmatched config or edit scope.\")\n    return roots",
        "lineStart": 1,
        "lineEnd": 117,
        "totalLines": 117,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716517406,
      "end": 1793716517410
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/env.py"
}

Output

<path>/source/head/fortinet/common/env.py</path>
<type>file</type>
<content>
1: """Environment variable compatibility helpers for Fortinet launchers."""
2: 
3: import os
4: 
5: 
6: def _candidate_names(name, aliases=(), legacy_aliases=()):
7:     """Yield preferred aliases, the FTNT spelling, then the original name."""
8:     seen = set()
9:     for candidate in aliases:
10:         if candidate not in seen:
11:             seen.add(candidate)
12:             yield candidate
13: 
14:     if name.startswith("FOS_"):
15:         ftnt_name = "FTNT_" + name[len("FOS_"):]
16:         if ftnt_name not in seen:
17:             seen.add(ftnt_name)
18:             yield ftnt_name
19: 
20:     if name not in seen:
21:         seen.add(name)
22:         yield name
23: 
24:     for candidate in legacy_aliases:
25:         if candidate not in seen:
26:             seen.add(candidate)
27:             yield candidate
28: 
29: 
30: def get_env(name, default=None, *, aliases=(), legacy_aliases=()):
31:     """Read an environment variable, preferring its FTNT spelling.
32: 
33:     ``aliases`` are checked first for renamed variables. ``legacy_aliases``
34:     are checked only after the canonical name to preserve older misspellings
35:     without allowing them to override a current spelling.
36:     """
37:     for candidate in _candidate_names(name, aliases, legacy_aliases):
38:         if candidate in os.environ:
39:             return os.environ[candidate]
40:     return default
41: 
42: 
43: def has_env(name, *, aliases=(), legacy_aliases=()):
44:     """Return whether any supported spelling is present in the environment."""
45:     return any(
46:         candidate in os.environ
47:         for candidate in _candidate_names(name, aliases, legacy_aliases)
48:     )

(End of file - total 48 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d5fa60001FC584Xmq32mcjj",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5d708001LvU45UtGXR2UuB",
  "callID": "call_b6fa5b822e9f4017a30d81e3",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/env.py"
    },
    "output": "<path>/source/head/fortinet/common/env.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Environment variable compatibility helpers for Fortinet launchers.\"\"\"\n2: \n3: import os\n4: \n5: \n6: def _candidate_names(name, aliases=(), legacy_aliases=()):\n7:     \"\"\"Yield preferred aliases, the FTNT spelling, then the original name.\"\"\"\n8:     seen = set()\n9:     for candidate in aliases:\n10:         if candidate not in seen:\n11:             seen.add(candidate)\n12:             yield candidate\n13: \n14:     if name.startswith(\"FOS_\"):\n15:         ftnt_name = \"FTNT_\" + name[len(\"FOS_\"):]\n16:         if ftnt_name not in seen:\n17:             seen.add(ftnt_name)\n18:             yield ftnt_name\n19: \n20:     if name not in seen:\n21:         seen.add(name)\n22:         yield name\n23: \n24:     for candidate in legacy_aliases:\n25:         if candidate not in seen:\n26:             seen.add(candidate)\n27:             yield candidate\n28: \n29: \n30: def get_env(name, default=None, *, aliases=(), legacy_aliases=()):\n31:     \"\"\"Read an environment variable, preferring its FTNT spelling.\n32: \n33:     ``aliases`` are checked first for renamed variables. ``legacy_aliases``\n34:     are checked only after the canonical name to preserve older misspellings\n35:     without allowing them to override a current spelling.\n36:     \"\"\"\n37:     for candidate in _candidate_names(name, aliases, legacy_aliases):\n38:         if candidate in os.environ:\n39:             return os.environ[candidate]\n40:     return default\n41: \n42: \n43: def has_env(name, *, aliases=(), legacy_aliases=()):\n44:     \"\"\"Return whether any supported spelling is present in the environment.\"\"\"\n45:     return any(\n46:         candidate in os.environ\n47:         for candidate in _candidate_names(name, aliases, legacy_aliases)\n48:     )\n\n(End of file - total 48 lines)\n</content>",
    "title": "source/head/fortinet/common/env.py",
    "metadata": {
      "preview": "\"\"\"Environment variable compatibility helpers for Fortinet launchers.\"\"\"\n\nimport os\n\n\ndef _candidate_names(name, aliases=(), legacy_aliases=()):\n    \"\"\"Yield preferred aliases, the FTNT spelling, then the original name.\"\"\"\n    seen = set()\n    for candidate in aliases:\n        if candidate not in seen:\n            seen.add(candidate)\n            yield candidate\n\n    if name.startswith(\"FOS_\"):\n        ftnt_name = \"FTNT_\" + name[len(\"FOS_\"):]\n        if ftnt_name not in seen:\n            seen.add(ftnt_name)\n            yield ftnt_name\n\n    if name not in seen:",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/env.py",
        "text": "\"\"\"Environment variable compatibility helpers for Fortinet launchers.\"\"\"\n\nimport os\n\n\ndef _candidate_names(name, aliases=(), legacy_aliases=()):\n    \"\"\"Yield preferred aliases, the FTNT spelling, then the original name.\"\"\"\n    seen = set()\n    for candidate in aliases:\n        if candidate not in seen:\n            seen.add(candidate)\n            yield candidate\n\n    if name.startswith(\"FOS_\"):\n        ftnt_name = \"FTNT_\" + name[len(\"FOS_\"):]\n        if ftnt_name not in seen:\n            seen.add(ftnt_name)\n            yield ftnt_name\n\n    if name not in seen:\n        seen.add(name)\n        yield name\n\n    for candidate in legacy_aliases:\n        if candidate not in seen:\n            seen.add(candidate)\n            yield candidate\n\n\ndef get_env(name, default=None, *, aliases=(), legacy_aliases=()):\n    \"\"\"Read an environment variable, preferring its FTNT spelling.\n\n    ``aliases`` are checked first for renamed variables. ``legacy_aliases``\n    are checked only after the canonical name to preserve older misspellings\n    without allowing them to override a current spelling.\n    \"\"\"\n    for candidate in _candidate_names(name, aliases, legacy_aliases):\n        if candidate in os.environ:\n            return os.environ[candidate]\n    return default\n\n\ndef has_env(name, *, aliases=(), legacy_aliases=()):\n    \"\"\"Return whether any supported spelling is present in the environment.\"\"\"\n    return any(\n        candidate in os.environ\n        for candidate in _candidate_names(name, aliases, legacy_aliases)\n    )",
        "lineStart": 1,
        "lineEnd": 48,
        "totalLines": 48,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716517476,
      "end": 1793716517481
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d5fa6b001eLnCKzZMKnQG0a",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5d708001LvU45UtGXR2UuB",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 88721,
    "input": 88239,
    "output": 77,
    "reasoning": 405,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d5d708001LvU45UtGXR2UuB",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716508424,
    "completed": 1793716517486
  },
  "parentID": "msg_1a1d3cdf3001rUzKxqKsJu9od7",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 88721,
    "input": 88239,
    "output": 77,
    "reasoning": 405,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 21
compaction
{
  "type": "compaction",
  "id": "prt_1a1d5fa71001SKXlLqA8Hhp8vi",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5fa70001QQwyKF3Xwh1ly5",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_1a1d5d708001LvU45UtGXR2UuB"
}
Message metadata
{
  "role": "user",
  "id": "msg_1a1d5fa70001QQwyKF3Xwh1ly5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716517488
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 22
step-start
{
  "type": "step-start",
  "id": "prt_1a1d603490014GxxmZke0o4E2a",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5fa85001ac7qVpVmxm8TOw"
}
Reasoning
Let me build the combined summary. Key updates from the conversation:

Completed now:
- grep on features for on_output/discard: only base.py (line 46 no-op hook returning False) and license.py (line 97) define on_output; features don't call expect/discard directly.
- Read launch.py (truncated, imports, signals, HEARTBEAT_FILE seen).
- Read test_common_admin_credentials.py (truncated), test_common_recovery.py (truncated), test_common_scope_errors.py (truncated), test_common_terminal_driver.py (first 600 lines, truncated), fos_commander.py (first 700 lines, truncated), cli_commands.py (truncated at CommandSpec __init__), fos_cli_driver.py (truncated at __init__), terminal.py (truncated at discard), features/base.py, features/license.py (truncated), test_common_stack_parsing.py (truncated), features/credentials.py (truncated), common.py first 120 lines (TRACE_LEVEL=9, FOSCliState enum with KERNEL_PANIC before UNKNOWN, BOOTSTRAP_HOSTNAME_REGEX, PROMPT_CONTEXT_REGEX, patterns).
- Read diff.txt offsets 1 and 1198 (already done per prior summary, re-confirmed).

Analysis conclusions reached in conversation:
- Driver forwarding: `process_state` → `_next_state` → if output and not matched: `commander.on_output(output)` once, then replaced with fresh empty Data. Matched output reaches commander via `on_state` → `on_output`. Each byte enters attempt.output at most once; matched Data is already consumed from buffer (no discard callback); timeout Data carries `_discard_prefix` callback; CommandAttempt.on_output captures+discards when capture_output or closes_scope. Duplicate-consumption concern (a) largely resolved.
- Concern (d) resolved: context-change after `next`/`end` is exempted via `_command_may_change_context`, so flow falls through to `_validate_completion` and closes_scope failures are always checked; `test_closing_failure_cannot_be_disabled_or_replayed` covers context change to "interface" — validation still runs.
- `_cleanup_retries` id(spec) keys: bounded/acceptable (P4 at most), specs retained in deques while keyed.
- `_restore_replay_context` None target: benign (block context never extractable).
- Session-loss-during-context-reset: `_context_reset_attempted` not reset, but bounded (one more abort attempt after reconnect); covered by `test_session_loss_during_context_reset_resumes_after_login`.
- License on_output: LICENSE_FAILURE_PATTERN search is idempotent, returns False, no duplicate-consumption correctness issue.
- parse_startup_config/_startup_config_quotes: quote/escape/continuation logic traced as correct; whitespace preservation in continuation lines verified; README claims consistent.
- flatten_commands/_flatten_quoted_lines: multi-line strings split into continuation commands; trailing newline stripped via strip(); empty middle lines sent as empty lines; CommandSpec ValueError for "\r" mid-string.
- FOSCliState enum: KERNEL_PANIC inserted before UNKNOWN (pattern state < UNKNOWN), consistent with driver `state.value < UNKNOWN` comparisons.
- TRACE_LEVEL = 9; change from TRACE_LEVEL-1 to TRACE_LEVEL fixes raw serial logging under "TRACE" level name registered in launch.py.
- on_state: CMD_PROMPT clears `_recovering`/sets `_authenticated_once` — intended "prompt ends session recovery".
- `_dispatch_command` with `_pending_feature_error` creates inflight without writing — discarded at recovery; acceptable.
- on_prompt_echo: matched Data has no discard callback; fallthrough writes b"\r" for clean prompt — by design.

Still remaining (Next Move):
- Read rest of fos_commander.py (lines 700+), fos_cli_driver.py (rest), terminal.py (rest), cli_commands.py (rest), launch.py (rest), common.py (rest of 120+), features/license.py rest, features/credentials.py rest, features/startup_config.py full, features/pki.py diff/comment.
- Read remaining test files fully: test_common_stack_boundaries.py, test_common_terminal_driver.py rest, and complete the truncated ones.
- Read both READMEs (fortigate/README.md, fortigate/docker/README.md).
- Finalize findings and emit trusted result schema, disclosing no-test-execution and snapshot incomplete: true.

Keep objective, constraints, file paths.
## Objective
- Perform a source-only, read-only PR review of the snapshot at `/source` (repo `srl-labs/vrnetlab`, head `1c29a33a37619b7547248e3b845130ba1f5f8ad0`, base `11dd16f88e2e5990de1061be498577af6c5d3552`), covering all 18 changed paths from `diff.txt`, then emit the trusted result schema (disclosing tests not executed; manifest indicates snapshot incomplete: true → report incomplete coverage).

## Important Details
- `standards.json` is empty (`[]`) — no rules to apply.
- 18 changed paths: M `fortinet/common/cli_commands.py`, `common.py`, `features/base.py`, `features/credentials.py`, `features/pki.py`, `features/startup_config.py`, `fos_cli_driver.py`, `fos_commander.py`, `launch.py`, `terminal.py`, `fortigate/README.md`, `fortigate/docker/README.md`, `tests/test_common_stack_boundaries.py`, `tests/test_common_stack_parsing.py`, `tests/test_common_terminal_driver.py`; A `tests/test_common_admin_credentials.py`, `tests/test_common_recovery.py`, `tests/test_common_scope_errors.py`.
- Read tool: bare `/source` directory read denied; must read specific files; truncated outputs need offset reads; batch independent calls.
- PR theme: FortiOS CLI stack rework — `ContextLossAction` (RESTART_BLOCK/FAIL), `CommandSpec.context_loss`/`continuation`, prompt-context tracking (`CLI_PROMPT_CONTEXT_PATTERN`, `BOOTSTRAP_HOSTNAME_REGEX`, `PROMPT_CONTEXT_REGEX`), scope-commit failure detection for `closes_scope` (`next`/`end` always capture; "Command fail. Return code -N" always fatal), abort-based context restore (`_context_reset_attempted`), `_recovery_retries` keyed by block_index, `_cleanup_retries` keyed by `id(spec)`, terminal `Data` timeout exposes FULL retained buffer (with `received_new_data` flag), env aliasing FTNT_*/FOS_* (env.py unchanged, load-bearing), `TRACE_LEVEL` (=9) logging change, `KernelPanicError` handling.
- `common.py` head facts: `TRACE_LEVEL = 9`; `FOSCliState` enum with `KERNEL_PANIC = auto()` inserted before `UNKNOWN` (pattern state < UNKNOWN, consistent with driver `state.value < UNKNOWN`); `BOOTSTRAP_HOSTNAME_REGEX` = GENERIC|DEFAULT|LICENSED hostname alternation; `PROMPT_CONTEXT_REGEX = rb"(?:[ \t]+\([^)]+\))*"`.
- Key data-flow verification (resolved prior concerns):
  - Driver `process_state` → `_next_state`: unmatched output forwarded to `commander.on_output` ONCE, then replaced with fresh empty `Data`; matched output reaches commander via `on_state` → `on_output`. Each byte enters `attempt.output` at most once — duplicate-consumption concern (a) largely RESOLVED.
  - Matched `Data` is already removed from buffer by `expect` (no discard callback); timeout `Data` carries `_discard_prefix` callback. `CommandAttempt.on_output` captures+discards when `capture_output` or `closes_scope`.
  - Concern (d) RESOLVED: context change after `next`/`end` is exempted via `_command_may_change_context`, so flow falls through to `_validate_completion` and closes_scope failure is always checked (test covers prompt context change to "interface").
  - `on_output` consumers: only `features/base.py` (line 46, no-op returning False) and `features/license.py` (line 97) define it; no features call `expect(`/`discard(` directly. License's `LICENSE_FAILURE_PATTERN.search` is idempotent — no correctness issue with repeated buffer views.
  - Concern (c) `_cleanup_retries` id(spec) keys: acceptable (specs retained in `_cleanup` deque while keyed); at most P4. Concern (b) `_restore_replay_context` None target: benign.
  - Session loss during context reset: `_context_reset_attempted` NOT reset → bounded (one more abort after reconnect); covered by `test_session_loss_during_context_reset_resumes_after_login`.
  - `on_state` CMD_PROMPT clearing `_recovering` at top: intended "prompt ends session recovery".
  - `_dispatch_command` with `_pending_feature_error` set: inflight created without write; discarded via `_recover_feature_error` at next CMD_PROMPT — acceptable.
  - `on_prompt_echo`: matched Data has no discard callback → `.discarded` False → writes `b"\r"` for clean prompt — by design.
  - `_startup_config_commands` quote/escape/continuation parsing traced correct: `\"` inside quotes handled, `\` line-continuation, continuation lines keep leading whitespace (only first line lstripped), `strip()` handles trailing newlines, embedded `\r` raises CommandSpec ValueError.
  - `flatten_commands`/`_flatten_quoted_lines`: plain multi-line strings split into continuation commands (`MULTILINE_PROMPT, CMD_PROMPT` completion for non-last lines); single line unchanged; empty middle lines sent as empty lines.
- credentials feature flow verified (prior work): `exit` lives in separate `admin-relogin` block; after end-logout, session-loss CONTINUE clears only current block, then `on_block_complete` submits exit block — matches tests.

## Work State
### Completed
- Read `/source/standards.json` (empty), `/source/manifest.json`, and full `/source/diff.txt` (offsets 1 and 1198).
- Read (all truncated at cut points): `cli_commands.py`, `common.py` (first 120 lines), `terminal.py` (Data/expect semantics visible), `fos_commander.py` (first ~700 lines), `fos_cli_driver.py` (first ~56 lines), `launch.py` (first ~61 lines), `features/base.py`, `features/credentials.py`, `features/license.py`, `features/startup_config.py`, `tests/test_common_stack_parsing.py`, `tests/test_common_terminal_driver.py` (first ~600 lines), `tests/test_common_admin_credentials.py`, `tests/test_common_recovery.py`, `tests/test_common_scope_errors.py`.
- Grep of `fortinet/common/features/`: only `base.py:46` and `license.py:97` define `on_output`; no direct `expect(`/`discard(` usage in features.
- Resolved all four previously-flagged concerns (duplicate timeout-Data consumption, None replay-target, id-keyed cleanup retries, context-loss-before-validation ordering) — none appear to be real P1/P2 findings.
- Verified env.py FTNT_*/FOS_* aliasing resolves test expectations; TRACE_LEVEL logging fix verified.

### Active
- Finishing per-file review of truncated head files: rest of `fos_commander.py` (700+), `fos_cli_driver.py` (56+), `terminal.py` (65+), `cli_commands.py` (CommandSpec init onward, CommandAttempt, closes_scope, flatten_commands), `launch.py` (61+), `common.py` (120+), `features/license.py`, `features/credentials.py`, full `features/startup_config.py`, `features/pki.py` (comment-only change).
- Reading remaining/complete test files: `tests/test_common_stack_boundaries.py`, rest of `test_common_terminal_driver.py`, rest of the three new test files and `test_common_stack_parsing.py`.
- Reading both READMEs: `fortigate/README.md`, `fortigate/docker/README.md`.

### Blocked
- (none)

## Next Move
1. Read remaining file segments with offsets: `fos_commander.py` (offset 700), `fos_cli_driver.py` (offset 56), `terminal.py` (offset 65), `cli_commands.py` (offset ~45), `launch.py` (offset 61), `common.py` (offset 120), plus full `features/license.py`, `features/credentials.py`, `features/startup_config.py`, `features/pki.py`.
2. Read remaining test files (`test_common_stack_boundaries.py`, rest of others) and both READMEs; then finalize findings and emit the trusted result schema, disclosing no-test-execution and manifest incomplete: true.

## Relevant Files
- `/source/manifest.json`, `/source/diff.txt`: inventory and full PR diff (both read).
- `/source/head/fortinet/common/cli_commands.py`: ContextLossAction, CommandSpec.context_loss/continuation, closes_scope, CommandAttempt.on_output, flatten_commands/_flatten_quoted_lines — partially read.
- `/source/head/fortinet/common/fos_commander.py`: core scheduler (scope-failure validation, context restore, retries) — partially read (lines 1–700).
- `/source/head/fortinet/common/terminal.py`: Data/expect full-buffer timeout semantics, received_new_data, discard callback — partially read.
- `/source/head/fortinet/common/fos_cli_driver.py`: stall detection, KernelPanicError, credential recovery — mostly unread (only ~56 lines).
- `/source/head/fortinet/common/launch.py`: KernelPanicError catch → stop + raise — mostly unread.
- `/source/head/fortinet/common/common.py`: TRACE_LEVEL=9, FOSCliState, regexes — read to line 120 only.
- `/source/head/fortinet/common/features/{base,license,credentials,startup_config,pki}.py`: feature lifecycle/output consumers — partially read.
- `/source/head/fortinet/tests/test_common_*.py`: all partially read; helpers (`RecordingFeature`, `SerialConnection`, `make_stack`) live in `test_common_stack_parsing.py`.
- `/source/head/fortinet/fortigate/README.md`, `/source/head/fortinet/fortigate/docker/README.md`: docs to review (not yet read).
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d645cf001A0qh7kl8ZymaAG",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d5fa85001ac7qVpVmxm8TOw",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 27062,
    "input": 24026,
    "output": 2125,
    "reasoning": 911,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d5fa85001ac7qVpVmxm8TOw",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716517509,
    "completed": 1793716536788
  },
  "parentID": "msg_1a1d5fa70001QQwyKF3Xwh1ly5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 27062,
    "input": 24026,
    "output": 2125,
    "reasoning": 911,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 23
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_1a1d645d70013gv2VsgIPALXxn",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716536791
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 24
step-start
{
  "type": "step-start",
  "id": "prt_1a1d64c1d001giAAvEif4l5Aop",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d645de0015j2Xa816gxTk2E"
}
Reasoning
I need to continue the review. Let me look at what's been done and what remains.

Done so far:
- Read manifest, diff, standards
- Read much of fos_commander.py (lines 1-700), cli_commands.py (partially), common.py (1-120), terminal.py (partially), fos_cli_driver.py (1-56), launch.py (1-61), features/base.py, features/license.py, features/credentials.py (partially), features/startup_config.py (full now), env.py (full now)
- Tests: test_common_stack_parsing.py (partially), test_common_terminal_driver.py (first 600), test_common_admin_credentials.py (truncated), test_common_recovery.py (truncated), test_common_scope_errors.py (truncated)

Remaining:
- Read rest of fos_commander.py (700+), fos_cli_driver.py (rest), terminal.py (rest), cli_commands.py (rest), launch.py (rest), common.py (rest of 120+), features/license.py rest, features/credentials.py rest, features/pki.py diff/comment
- Read remaining test files fully: test_common_stack_boundaries.py, test_common_terminal_driver.py rest, and complete the truncated ones
- Read both READMEs

Note: I noticed something in startup_config.py worth checking. The quote tracking: `elif character == quote: quote = None` — but wait, in the loop, when `escaped` is True, the next character is consumed. But there's a subtle bug: if `escaped` is True at end of line (backslash at line end), the `escaped` state is carried via the `pending.append(line); continue` path, but `escaped` is a local variable reset to False at the start of the next line iteration. So a trailing backslash (line continuation) keeps the line pending — that's the intent ("unfinished line continuation"). But the `escaped` flag carrying into the next line is lost: e.g. `"abc\` + next line `def"` — the backslash escapes the newline, so on the next line, the first character could be a quote that should be treated as a literal? Actually in CLI semantics, `\` at end of line continues the line. Hmm, in the parser, when escaped is True at the end of processing a line, the line is appended to pending and loop continues; next iteration `escaped = False` is reset. So a `\` before the newline acts as line continuation but the escape itself is not carried into the next line's first character. That matches shell-like behavior where backslash-newline is a line continuation, not an escaped newline. Fine.

Another consideration: `line.rstrip()` on the final line of a command but `pending.append(line)` (no rstrip) for continuation lines — preserves interior whitespace intentionally, per comment. Good.

Potential issue: `elif character == quote: quote = None` — if quote is None (no open quote) and character is `'` or `"`, opens quote. But if quote is None and character is `\` followed by nothing... covered.

Edge: unbalanced quotes across lines — quote state persists across lines since it's in the function scope. Good.

Another edge: `for character in line: if escaped: escaped = False` — this treats any character after backslash as escaped, including quotes, so `"\""` — opens quote at char 0? Let's trace: char `"` with quote None → quote='"'. char `\` → escaped=True. char `"` → escaped consumed, quote stays '"'. char `"` → matches quote → quote=None. So `"\""` is a complete quoted string. Good.

Now let me continue reading files. I should read the remaining parts in parallel batches:

Batch 1:
- fos_commander.py offset 700
- fos_cli_driver.py offset 56
- terminal.py offset 65
- cli_commands.py offset 45 (CommandSpec init onward)

Batch 2:
- launch.py offset 61
- common.py offset 120
- features/license.py
- features/credentials.py

Batch 3:
- features/pki.py
- test_common_stack_boundaries.py
- test_common_terminal_driver.py offset 600
- test_common_stack_parsing.py offset (where it left off)

Batch 4:
- READMEs
- rest of test files

Let me start. I'll do a big batch of parallel reads.
Continuing. Let me read the remaining segments of the core files in parallel.
read · error

Input

{
  "filePath": "/source/head/fortinet/common/fos_commander.py",
  "offset": 700
}

Output

Offset 700 is out of range for this file (687 lines)
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d66607001GGwyXHzwWMjSmN",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d645de0015j2Xa816gxTk2E",
  "callID": "call_74e8221be4434ff2be4e19b8",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_commander.py",
      "offset": 700
    },
    "error": "Offset 700 is out of range for this file (687 lines)",
    "time": {
      "start": 1793716545036,
      "end": 1793716545042
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_cli_driver.py",
  "offset": 56
}

Output

<path>/source/head/fortinet/common/fos_cli_driver.py</path>
<type>file</type>
<content>
56:         self._awaiting_login_acceptance = False
57:         self._credential_recovery_pending = False
58:         self._pending_bootstrap_activation = False
59:         self._unknown_started_at = None
60:         self._unknown_newlines = 0
61:         self._state_handlers = {
62:             FOSCliState.PROVIDE_USERNAME: self._provide_username,
63:             FOSCliState.PROVIDE_PASSWORD: self._provide_password,
64:             FOSCliState.CURRENT_PASSWORD: self._provide_current_password,
65:             FOSCliState.CHANGE_PASSWORD: self._provide_new_password,
66:             FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,
67:             FOSCliState.MORE_PROMPT: self._continue_pager,
68:             FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,
69:             FOSCliState.CMD_PROMPT: self._command_prompt,
70:             FOSCliState.CMD_PROMPT_ECHO: None,
71:             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,
72:             FOSCliState.LIC_FAIL: self._license_failed,
73:             FOSCliState.TN_TIMEOUT: self._timeout,
74:             FOSCliState.KERNEL_PANIC: self._kernel_panic,
75:             FOSCliState.UNKNOWN: self._unknown,
76:         }
77: 
78:     @property
79:     def state_patterns(self):
80:         return self._state_patterns
81: 
82:     @property
83:     def ready(self):
84:         return self._commander.ready
85: 
86:     def remember_current_credentials(self):
87:         """Keep the last accepted credentials for a failed password transition."""
88:         if self._recovery_credentials is not None or self._recovery_attempted:
89:             return
90:         self._recovery_credentials = (
91:             self._credentials.username,
92:             self._credentials.password,
93:         )
94:         self._recovery_attempted = False
95: 
96:     @property
97:     def at_command_prompt(self):
98:         """Whether the most recent console event left FortiOS at a CLI prompt."""
99:         return self._current_state == FOSCliState.CMD_PROMPT or (
100:             self._current_state == FOSCliState.TN_TIMEOUT
101:             and self._last_known_state == FOSCliState.CMD_PROMPT
102:         )
103: 
104:     def process_state(self):
105:         spin_start = time.time()
106:         while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:
107:             state, output, matched = self._next_state()
108:             self._current_state = state
109:             if output and not matched:
110:                 self._commander.on_output(output)
111:                 if state == FOSCliState.UNKNOWN:
112:                     self._note_unknown_output()
113:                 output = type(output)(b"")
114:             if state.value < FOSCliState.UNKNOWN.value:
115:                 self._idle_spins = 0
116:                 self._last_known_state = state
117:                 self._clear_unknown_stall()
118:                 self._log_state(state)
119:             self._process_state(state, output)
120: 
121:     def _log_state(self, state):
122:         if state == FOSCliState.MULTILINE_PROMPT:
123:             return
124:         if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:
125:             return
126:         self._last_logged_state = state
127:         self._logger.debug(f"ST: {state.name}")
128: 
129:     def _process_state(self, state, output):
130:         """Handle a CLI state and then let the commander observe it.
131: 
132:         A password confirmation can be followed immediately by a command
133:         prompt, without ``Welcome!``.  Apply that credential transition
134:         before the commander dispatches the command associated with the
135:         prompt.
136:         """
137:         if state == FOSCliState.CMD_PROMPT:
138:             self._handle_state(state)
139:         if state == FOSCliState.CMD_PROMPT_ECHO:
140:             self._commander.on_prompt_echo(output)
141:         else:
142:             self._commander.on_state(state, output)
143:         if state != FOSCliState.CMD_PROMPT:
144:             self._handle_state(state)
145:         if state == FOSCliState.CMD_PROMPT:
146:             self._commander.tick()
147:         elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:
148:             self._commander.tick()
149:             self._commander.on_idle_prompt()
150: 
151:     def _next_state(self):
152:         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)
153:         if match:
154:             return FOSCliState(index), output, True
155:         # A timeout exposes retained bytes too. Only fresh input should reset
156:         # the unknown-output stall timer; an unchanged buffer is still idle.
157:         state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT
158:         return state, output, False
159: 
160:     def _handle_state(self, state):
161:         handler = self._state_handlers.get(state)
162:         if handler:
163:             try:
164:                 handler()
165:             except Exception:
166:                 self._logger.exception("CLI state handler failed for %s", state.name)
167:                 raise
168: 
169:     def _provide_username(self):
170:         username = self._credentials.username
171:         if self._use_recovery_credentials and self._recovery_credentials is not None:
172:             username = self._recovery_credentials[0]
173:         self._awaiting_login_acceptance = True
174:         self._respond(FOSCliState.PROVIDE_USERNAME, username)
175: 
176:     def _provide_password(self):
177:         if self._send_blank_password:
178:             # The initial blank-password fallback is consumed as soon as it is
179:             # sent. Later credential recovery is managed separately.
180:             self._send_blank_password = False
181:             self._blank_fallback_available = False
182:             self._activate_blank_credentials()
183:             self._respond(FOSCliState.PROVIDE_PASSWORD, b"")
184:             return
185:         if self._use_recovery_credentials and self._recovery_credentials is not None:
186:             self._respond(
187:                 FOSCliState.PROVIDE_PASSWORD,
188:                 self._recovery_credentials[1],
189:             )
190:             return
191:         self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)
192: 
193:     def _provide_current_password(self):
194:         self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)
195: 
196:     def _provide_new_password(self):
197:         self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)
198: 
199:     def _confirm_new_password(self):
200:         self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)
201:         # Do not update active credentials until FortiOS accepts the
202:         # confirmation. A rejected confirmation leaves the active password
203:         # unchanged so that subsequent prompts use the right value.
204:         self._pending_bootstrap_activation = True
205: 
206:     def _continue_pager(self):
207:         self._terminal.write(b" ")
208: 
209:     def _credential_accepted(self):
210:         self._accept_login()
211: 
212:     def _accept_login(self):
213:         self._initial_login_complete = True
214:         self._awaiting_login_acceptance = False
215:         recovered = (
216:             self._use_recovery_credentials
217:             and self._recovery_credentials is not None
218:         )
219:         if recovered:
220:             self._use_recovery_credentials = False
221:             self._recovery_attempted = False
222:             if not self._credential_recovery_pending:
223:                 self._commander.record_feature_error(
224:                     "admin-credentials",
225:                     "desired credentials were rejected; resumed with the previous credentials "
226:                     "while keeping the desired credentials for later logins",
227:                 )
228:             self._credential_recovery_pending = True
229:         elif self._recovery_credentials is not None:
230:             self._recovery_attempted = False
231:             if self._credential_recovery_pending:
232:                 self._commander.resolve_feature_error(
233:                     "admin-credentials",
234:                     "the desired credentials authenticated successfully",
235:                 )
236:                 self._credential_recovery_pending = False
237:         self._activate_pending_bootstrap_credentials()
238: 
239:     def _command_prompt(self):
240:         """Accept password confirmation on versions that skip ``Welcome!``."""
241:         if self._awaiting_login_acceptance:
242:             self._accept_login()
243:         else:
244:             self._initial_login_complete = True
245:             self._activate_pending_bootstrap_credentials()
246: 
247:     def _activate_pending_bootstrap_credentials(self):
248:         if self._pending_bootstrap_activation:
249:             self._activate_bootstrap_credentials()
250:             self._pending_bootstrap_activation = False
251: 
252:     @staticmethod
253:     def _license_failed():
254:         # SetLicense inspects the buffered command output when FortiOS returns
255:         # to a prompt. Raising here would interrupt the driver at LIC_FAIL,
256:         # before best-effort bootstrap can safely skip the feature.
257:         return None
258: 
259:     def _timeout(self):
260:         self._idle_spins += 1
261:         self._recover_unknown_stall()
262: 
263:     def _unknown(self):
264:         if self._last_known_state == FOSCliState.REBOOTING:
265:             self._idle_spins += 1
266: 
267:     @staticmethod
268:     def _kernel_panic():
269:         raise KernelPanicError("Kernel panic detected on serial console")
270: 
271:     def _note_unknown_output(self):
272:         self._unknown_started_at = time.monotonic()
273: 
274:     def _recover_unknown_stall(self):
275:         if self._unknown_started_at is None:
276:             return
277:         if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:
278:             return
279:         if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:
280:             raise RuntimeError("CLI remained in unknown state")
281:         self._unknown_newlines += 1
282:         self._unknown_started_at = time.monotonic()
283:         self._logger.warning(
284:             "CLI stuck in unknown state; sending newline "
285:             f"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})"
286:         )
287:         self._terminal.write(b"\r")
288: 
289:     def _clear_unknown_stall(self):
290:         self._unknown_started_at = None
291:         self._unknown_newlines = 0
292: 
293:     def set_prompt_patterns(self, name_pattern):
294:         if isinstance(name_pattern, str):
295:             name_pattern = re.escape(name_pattern.encode())
296:         self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb"(?m)^[ \t]*" + name_pattern + rb"[ \t]+login:[ \t]*"
297:         self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*\r?$"
298:         self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*[^\r\n]+(?:\r?\n)?"
299: 
300:     def _credential_rejected(self):
301:         # A rejected interaction cannot establish the newly selected
302:         # bootstrap password.  Do not activate it on a later unrelated
303:         # acceptance or prompt.
304:         self._pending_bootstrap_activation = False
305:         if not self._initial_login_complete and self._blank_fallback_available:
306:             self._send_blank_password = True
307:             return
308:         if (
309:             self._allow_credential_recovery
310:             and self._recovery_credentials is not None
311:             and not self._recovery_attempted
312:         ):
313:             self._recovery_attempted = True
314:             self._use_recovery_credentials = True
315:             self._logger.warning(
316:                 "Credentials were rejected; retrying with the previously accepted credentials"
317:             )
318:             return
319:         raise RuntimeError("Credential rejected")
320: 
321:     def _respond(self, state, response):
322:         """Write an interactive response to the CLI."""
323:         if isinstance(response, str):
324:             response = response.encode()
325:         self._logger.log(
326:             TRACE_LEVEL,
327:             "Responding to CLI state %s with '%s'",
328:             state.name,
329:             response,
330:         )
331:         self._terminal.write(bytes(response) + b"\r")

(End of file - total 331 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d66661001rTfCe5XAeGKy3M",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d645de0015j2Xa816gxTk2E",
  "callID": "call_8a90e3d3d9a24ede93d17d00",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_cli_driver.py",
      "offset": 56
    },
    "output": "<path>/source/head/fortinet/common/fos_cli_driver.py</path>\n<type>file</type>\n<content>\n56:         self._awaiting_login_acceptance = False\n57:         self._credential_recovery_pending = False\n58:         self._pending_bootstrap_activation = False\n59:         self._unknown_started_at = None\n60:         self._unknown_newlines = 0\n61:         self._state_handlers = {\n62:             FOSCliState.PROVIDE_USERNAME: self._provide_username,\n63:             FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n64:             FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n65:             FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n66:             FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n67:             FOSCliState.MORE_PROMPT: self._continue_pager,\n68:             FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n69:             FOSCliState.CMD_PROMPT: self._command_prompt,\n70:             FOSCliState.CMD_PROMPT_ECHO: None,\n71:             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n72:             FOSCliState.LIC_FAIL: self._license_failed,\n73:             FOSCliState.TN_TIMEOUT: self._timeout,\n74:             FOSCliState.KERNEL_PANIC: self._kernel_panic,\n75:             FOSCliState.UNKNOWN: self._unknown,\n76:         }\n77: \n78:     @property\n79:     def state_patterns(self):\n80:         return self._state_patterns\n81: \n82:     @property\n83:     def ready(self):\n84:         return self._commander.ready\n85: \n86:     def remember_current_credentials(self):\n87:         \"\"\"Keep the last accepted credentials for a failed password transition.\"\"\"\n88:         if self._recovery_credentials is not None or self._recovery_attempted:\n89:             return\n90:         self._recovery_credentials = (\n91:             self._credentials.username,\n92:             self._credentials.password,\n93:         )\n94:         self._recovery_attempted = False\n95: \n96:     @property\n97:     def at_command_prompt(self):\n98:         \"\"\"Whether the most recent console event left FortiOS at a CLI prompt.\"\"\"\n99:         return self._current_state == FOSCliState.CMD_PROMPT or (\n100:             self._current_state == FOSCliState.TN_TIMEOUT\n101:             and self._last_known_state == FOSCliState.CMD_PROMPT\n102:         )\n103: \n104:     def process_state(self):\n105:         spin_start = time.time()\n106:         while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:\n107:             state, output, matched = self._next_state()\n108:             self._current_state = state\n109:             if output and not matched:\n110:                 self._commander.on_output(output)\n111:                 if state == FOSCliState.UNKNOWN:\n112:                     self._note_unknown_output()\n113:                 output = type(output)(b\"\")\n114:             if state.value < FOSCliState.UNKNOWN.value:\n115:                 self._idle_spins = 0\n116:                 self._last_known_state = state\n117:                 self._clear_unknown_stall()\n118:                 self._log_state(state)\n119:             self._process_state(state, output)\n120: \n121:     def _log_state(self, state):\n122:         if state == FOSCliState.MULTILINE_PROMPT:\n123:             return\n124:         if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:\n125:             return\n126:         self._last_logged_state = state\n127:         self._logger.debug(f\"ST: {state.name}\")\n128: \n129:     def _process_state(self, state, output):\n130:         \"\"\"Handle a CLI state and then let the commander observe it.\n131: \n132:         A password confirmation can be followed immediately by a command\n133:         prompt, without ``Welcome!``.  Apply that credential transition\n134:         before the commander dispatches the command associated with the\n135:         prompt.\n136:         \"\"\"\n137:         if state == FOSCliState.CMD_PROMPT:\n138:             self._handle_state(state)\n139:         if state == FOSCliState.CMD_PROMPT_ECHO:\n140:             self._commander.on_prompt_echo(output)\n141:         else:\n142:             self._commander.on_state(state, output)\n143:         if state != FOSCliState.CMD_PROMPT:\n144:             self._handle_state(state)\n145:         if state == FOSCliState.CMD_PROMPT:\n146:             self._commander.tick()\n147:         elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:\n148:             self._commander.tick()\n149:             self._commander.on_idle_prompt()\n150: \n151:     def _next_state(self):\n152:         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n153:         if match:\n154:             return FOSCliState(index), output, True\n155:         # A timeout exposes retained bytes too. Only fresh input should reset\n156:         # the unknown-output stall timer; an unchanged buffer is still idle.\n157:         state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n158:         return state, output, False\n159: \n160:     def _handle_state(self, state):\n161:         handler = self._state_handlers.get(state)\n162:         if handler:\n163:             try:\n164:                 handler()\n165:             except Exception:\n166:                 self._logger.exception(\"CLI state handler failed for %s\", state.name)\n167:                 raise\n168: \n169:     def _provide_username(self):\n170:         username = self._credentials.username\n171:         if self._use_recovery_credentials and self._recovery_credentials is not None:\n172:             username = self._recovery_credentials[0]\n173:         self._awaiting_login_acceptance = True\n174:         self._respond(FOSCliState.PROVIDE_USERNAME, username)\n175: \n176:     def _provide_password(self):\n177:         if self._send_blank_password:\n178:             # The initial blank-password fallback is consumed as soon as it is\n179:             # sent. Later credential recovery is managed separately.\n180:             self._send_blank_password = False\n181:             self._blank_fallback_available = False\n182:             self._activate_blank_credentials()\n183:             self._respond(FOSCliState.PROVIDE_PASSWORD, b\"\")\n184:             return\n185:         if self._use_recovery_credentials and self._recovery_credentials is not None:\n186:             self._respond(\n187:                 FOSCliState.PROVIDE_PASSWORD,\n188:                 self._recovery_credentials[1],\n189:             )\n190:             return\n191:         self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)\n192: \n193:     def _provide_current_password(self):\n194:         self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)\n195: \n196:     def _provide_new_password(self):\n197:         self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)\n198: \n199:     def _confirm_new_password(self):\n200:         self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)\n201:         # Do not update active credentials until FortiOS accepts the\n202:         # confirmation. A rejected confirmation leaves the active password\n203:         # unchanged so that subsequent prompts use the right value.\n204:         self._pending_bootstrap_activation = True\n205: \n206:     def _continue_pager(self):\n207:         self._terminal.write(b\" \")\n208: \n209:     def _credential_accepted(self):\n210:         self._accept_login()\n211: \n212:     def _accept_login(self):\n213:         self._initial_login_complete = True\n214:         self._awaiting_login_acceptance = False\n215:         recovered = (\n216:             self._use_recovery_credentials\n217:             and self._recovery_credentials is not None\n218:         )\n219:         if recovered:\n220:             self._use_recovery_credentials = False\n221:             self._recovery_attempted = False\n222:             if not self._credential_recovery_pending:\n223:                 self._commander.record_feature_error(\n224:                     \"admin-credentials\",\n225:                     \"desired credentials were rejected; resumed with the previous credentials \"\n226:                     \"while keeping the desired credentials for later logins\",\n227:                 )\n228:             self._credential_recovery_pending = True\n229:         elif self._recovery_credentials is not None:\n230:             self._recovery_attempted = False\n231:             if self._credential_recovery_pending:\n232:                 self._commander.resolve_feature_error(\n233:                     \"admin-credentials\",\n234:                     \"the desired credentials authenticated successfully\",\n235:                 )\n236:                 self._credential_recovery_pending = False\n237:         self._activate_pending_bootstrap_credentials()\n238: \n239:     def _command_prompt(self):\n240:         \"\"\"Accept password confirmation on versions that skip ``Welcome!``.\"\"\"\n241:         if self._awaiting_login_acceptance:\n242:             self._accept_login()\n243:         else:\n244:             self._initial_login_complete = True\n245:             self._activate_pending_bootstrap_credentials()\n246: \n247:     def _activate_pending_bootstrap_credentials(self):\n248:         if self._pending_bootstrap_activation:\n249:             self._activate_bootstrap_credentials()\n250:             self._pending_bootstrap_activation = False\n251: \n252:     @staticmethod\n253:     def _license_failed():\n254:         # SetLicense inspects the buffered command output when FortiOS returns\n255:         # to a prompt. Raising here would interrupt the driver at LIC_FAIL,\n256:         # before best-effort bootstrap can safely skip the feature.\n257:         return None\n258: \n259:     def _timeout(self):\n260:         self._idle_spins += 1\n261:         self._recover_unknown_stall()\n262: \n263:     def _unknown(self):\n264:         if self._last_known_state == FOSCliState.REBOOTING:\n265:             self._idle_spins += 1\n266: \n267:     @staticmethod\n268:     def _kernel_panic():\n269:         raise KernelPanicError(\"Kernel panic detected on serial console\")\n270: \n271:     def _note_unknown_output(self):\n272:         self._unknown_started_at = time.monotonic()\n273: \n274:     def _recover_unknown_stall(self):\n275:         if self._unknown_started_at is None:\n276:             return\n277:         if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:\n278:             return\n279:         if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:\n280:             raise RuntimeError(\"CLI remained in unknown state\")\n281:         self._unknown_newlines += 1\n282:         self._unknown_started_at = time.monotonic()\n283:         self._logger.warning(\n284:             \"CLI stuck in unknown state; sending newline \"\n285:             f\"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})\"\n286:         )\n287:         self._terminal.write(b\"\\r\")\n288: \n289:     def _clear_unknown_stall(self):\n290:         self._unknown_started_at = None\n291:         self._unknown_newlines = 0\n292: \n293:     def set_prompt_patterns(self, name_pattern):\n294:         if isinstance(name_pattern, str):\n295:             name_pattern = re.escape(name_pattern.encode())\n296:         self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb\"(?m)^[ \\t]*\" + name_pattern + rb\"[ \\t]+login:[ \\t]*\"\n297:         self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n298:         self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n299: \n300:     def _credential_rejected(self):\n301:         # A rejected interaction cannot establish the newly selected\n302:         # bootstrap password.  Do not activate it on a later unrelated\n303:         # acceptance or prompt.\n304:         self._pending_bootstrap_activation = False\n305:         if not self._initial_login_complete and self._blank_fallback_available:\n306:             self._send_blank_password = True\n307:             return\n308:         if (\n309:             self._allow_credential_recovery\n310:             and self._recovery_credentials is not None\n311:             and not self._recovery_attempted\n312:         ):\n313:             self._recovery_attempted = True\n314:             self._use_recovery_credentials = True\n315:             self._logger.warning(\n316:                 \"Credentials were rejected; retrying with the previously accepted credentials\"\n317:             )\n318:             return\n319:         raise RuntimeError(\"Credential rejected\")\n320: \n321:     def _respond(self, state, response):\n322:         \"\"\"Write an interactive response to the CLI.\"\"\"\n323:         if isinstance(response, str):\n324:             response = response.encode()\n325:         self._logger.log(\n326:             TRACE_LEVEL,\n327:             \"Responding to CLI state %s with '%s'\",\n328:             state.name,\n329:             response,\n330:         )\n331:         self._terminal.write(bytes(response) + b\"\\r\")\n\n(End of file - total 331 lines)\n</content>",
    "title": "source/head/fortinet/common/fos_cli_driver.py",
    "metadata": {
      "preview": "        self._awaiting_login_acceptance = False\n        self._credential_recovery_pending = False\n        self._pending_bootstrap_activation = False\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n        self._state_handlers = {\n            FOSCliState.PROVIDE_USERNAME: self._provide_username,\n            FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n            FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n            FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n            FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n            FOSCliState.MORE_PROMPT: self._continue_pager,\n            FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n            FOSCliState.CMD_PROMPT: self._command_prompt,\n            FOSCliState.CMD_PROMPT_ECHO: None,\n            FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n            FOSCliState.LIC_FAIL: self._license_failed,\n            FOSCliState.TN_TIMEOUT: self._timeout,\n            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n            FOSCliState.UNKNOWN: self._unknown,",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_cli_driver.py",
        "text": "        self._awaiting_login_acceptance = False\n        self._credential_recovery_pending = False\n        self._pending_bootstrap_activation = False\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n        self._state_handlers = {\n            FOSCliState.PROVIDE_USERNAME: self._provide_username,\n            FOSCliState.PROVIDE_PASSWORD: self._provide_password,\n            FOSCliState.CURRENT_PASSWORD: self._provide_current_password,\n            FOSCliState.CHANGE_PASSWORD: self._provide_new_password,\n            FOSCliState.CHANGE_PASSWORD_CONFIRM: self._confirm_new_password,\n            FOSCliState.MORE_PROMPT: self._continue_pager,\n            FOSCliState.CREDENTIAL_ACCEPTED: self._credential_accepted,\n            FOSCliState.CMD_PROMPT: self._command_prompt,\n            FOSCliState.CMD_PROMPT_ECHO: None,\n            FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n            FOSCliState.LIC_FAIL: self._license_failed,\n            FOSCliState.TN_TIMEOUT: self._timeout,\n            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n            FOSCliState.UNKNOWN: self._unknown,\n        }\n\n    @property\n    def state_patterns(self):\n        return self._state_patterns\n\n    @property\n    def ready(self):\n        return self._commander.ready\n\n    def remember_current_credentials(self):\n        \"\"\"Keep the last accepted credentials for a failed password transition.\"\"\"\n        if self._recovery_credentials is not None or self._recovery_attempted:\n            return\n        self._recovery_credentials = (\n            self._credentials.username,\n            self._credentials.password,\n        )\n        self._recovery_attempted = False\n\n    @property\n    def at_command_prompt(self):\n        \"\"\"Whether the most recent console event left FortiOS at a CLI prompt.\"\"\"\n        return self._current_state == FOSCliState.CMD_PROMPT or (\n            self._current_state == FOSCliState.TN_TIMEOUT\n            and self._last_known_state == FOSCliState.CMD_PROMPT\n        )\n\n    def process_state(self):\n        spin_start = time.time()\n        while not self.ready and time.time() < spin_start + PROCESS_SPIN_SECONDS:\n            state, output, matched = self._next_state()\n            self._current_state = state\n            if output and not matched:\n                self._commander.on_output(output)\n                if state == FOSCliState.UNKNOWN:\n                    self._note_unknown_output()\n                output = type(output)(b\"\")\n            if state.value < FOSCliState.UNKNOWN.value:\n                self._idle_spins = 0\n                self._last_known_state = state\n                self._clear_unknown_stall()\n                self._log_state(state)\n            self._process_state(state, output)\n\n    def _log_state(self, state):\n        if state == FOSCliState.MULTILINE_PROMPT:\n            return\n        if state == FOSCliState.CMD_PROMPT and self._last_logged_state == state:\n            return\n        self._last_logged_state = state\n        self._logger.debug(f\"ST: {state.name}\")\n\n    def _process_state(self, state, output):\n        \"\"\"Handle a CLI state and then let the commander observe it.\n\n        A password confirmation can be followed immediately by a command\n        prompt, without ``Welcome!``.  Apply that credential transition\n        before the commander dispatches the command associated with the\n        prompt.\n        \"\"\"\n        if state == FOSCliState.CMD_PROMPT:\n            self._handle_state(state)\n        if state == FOSCliState.CMD_PROMPT_ECHO:\n            self._commander.on_prompt_echo(output)\n        else:\n            self._commander.on_state(state, output)\n        if state != FOSCliState.CMD_PROMPT:\n            self._handle_state(state)\n        if state == FOSCliState.CMD_PROMPT:\n            self._commander.tick()\n        elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == FOSCliState.CMD_PROMPT:\n            self._commander.tick()\n            self._commander.on_idle_prompt()\n\n    def _next_state(self):\n        index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n        if match:\n            return FOSCliState(index), output, True\n        # A timeout exposes retained bytes too. Only fresh input should reset\n        # the unknown-output stall timer; an unchanged buffer is still idle.\n        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n        return state, output, False\n\n    def _handle_state(self, state):\n        handler = self._state_handlers.get(state)\n        if handler:\n            try:\n                handler()\n            except Exception:\n                self._logger.exception(\"CLI state handler failed for %s\", state.name)\n                raise\n\n    def _provide_username(self):\n        username = self._credentials.username\n        if self._use_recovery_credentials and self._recovery_credentials is not None:\n            username = self._recovery_credentials[0]\n        self._awaiting_login_acceptance = True\n        self._respond(FOSCliState.PROVIDE_USERNAME, username)\n\n    def _provide_password(self):\n        if self._send_blank_password:\n            # The initial blank-password fallback is consumed as soon as it is\n            # sent. Later credential recovery is managed separately.\n            self._send_blank_password = False\n            self._blank_fallback_available = False\n            self._activate_blank_credentials()\n            self._respond(FOSCliState.PROVIDE_PASSWORD, b\"\")\n            return\n        if self._use_recovery_credentials and self._recovery_credentials is not None:\n            self._respond(\n                FOSCliState.PROVIDE_PASSWORD,\n                self._recovery_credentials[1],\n            )\n            return\n        self._respond(FOSCliState.PROVIDE_PASSWORD, self._credentials.password)\n\n    def _provide_current_password(self):\n        self._respond(FOSCliState.CURRENT_PASSWORD, self._credentials.password)\n\n    def _provide_new_password(self):\n        self._respond(FOSCliState.CHANGE_PASSWORD, self._bootstrap_password)\n\n    def _confirm_new_password(self):\n        self._respond(FOSCliState.CHANGE_PASSWORD_CONFIRM, self._bootstrap_password)\n        # Do not update active credentials until FortiOS accepts the\n        # confirmation. A rejected confirmation leaves the active password\n        # unchanged so that subsequent prompts use the right value.\n        self._pending_bootstrap_activation = True\n\n    def _continue_pager(self):\n        self._terminal.write(b\" \")\n\n    def _credential_accepted(self):\n        self._accept_login()\n\n    def _accept_login(self):\n        self._initial_login_complete = True\n        self._awaiting_login_acceptance = False\n        recovered = (\n            self._use_recovery_credentials\n            and self._recovery_credentials is not None\n        )\n        if recovered:\n            self._use_recovery_credentials = False\n            self._recovery_attempted = False\n            if not self._credential_recovery_pending:\n                self._commander.record_feature_error(\n                    \"admin-credentials\",\n                    \"desired credentials were rejected; resumed with the previous credentials \"\n                    \"while keeping the desired credentials for later logins\",\n                )\n            self._credential_recovery_pending = True\n        elif self._recovery_credentials is not None:\n            self._recovery_attempted = False\n            if self._credential_recovery_pending:\n                self._commander.resolve_feature_error(\n                    \"admin-credentials\",\n                    \"the desired credentials authenticated successfully\",\n                )\n                self._credential_recovery_pending = False\n        self._activate_pending_bootstrap_credentials()\n\n    def _command_prompt(self):\n        \"\"\"Accept password confirmation on versions that skip ``Welcome!``.\"\"\"\n        if self._awaiting_login_acceptance:\n            self._accept_login()\n        else:\n            self._initial_login_complete = True\n            self._activate_pending_bootstrap_credentials()\n\n    def _activate_pending_bootstrap_credentials(self):\n        if self._pending_bootstrap_activation:\n            self._activate_bootstrap_credentials()\n            self._pending_bootstrap_activation = False\n\n    @staticmethod\n    def _license_failed():\n        # SetLicense inspects the buffered command output when FortiOS returns\n        # to a prompt. Raising here would interrupt the driver at LIC_FAIL,\n        # before best-effort bootstrap can safely skip the feature.\n        return None\n\n    def _timeout(self):\n        self._idle_spins += 1\n        self._recover_unknown_stall()\n\n    def _unknown(self):\n        if self._last_known_state == FOSCliState.REBOOTING:\n            self._idle_spins += 1\n\n    @staticmethod\n    def _kernel_panic():\n        raise KernelPanicError(\"Kernel panic detected on serial console\")\n\n    def _note_unknown_output(self):\n        self._unknown_started_at = time.monotonic()\n\n    def _recover_unknown_stall(self):\n        if self._unknown_started_at is None:\n            return\n        if time.monotonic() - self._unknown_started_at < UNKNOWN_STALL_SECONDS:\n            return\n        if self._unknown_newlines >= UNKNOWN_STALL_NEWLINE_LIMIT:\n            raise RuntimeError(\"CLI remained in unknown state\")\n        self._unknown_newlines += 1\n        self._unknown_started_at = time.monotonic()\n        self._logger.warning(\n            \"CLI stuck in unknown state; sending newline \"\n            f\"({self._unknown_newlines}/{UNKNOWN_STALL_NEWLINE_LIMIT})\"\n        )\n        self._terminal.write(b\"\\r\")\n\n    def _clear_unknown_stall(self):\n        self._unknown_started_at = None\n        self._unknown_newlines = 0\n\n    def set_prompt_patterns(self, name_pattern):\n        if isinstance(name_pattern, str):\n            name_pattern = re.escape(name_pattern.encode())\n        self._state_patterns[FOSCliState.PROVIDE_USERNAME.value] = rb\"(?m)^[ \\t]*\" + name_pattern + rb\"[ \\t]+login:[ \\t]*\"\n        self._state_patterns[FOSCliState.CMD_PROMPT.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*\\r?$\"\n        self._state_patterns[FOSCliState.CMD_PROMPT_ECHO.value] = rb\"(?m)^[ \\t]*\" + name_pattern + PROMPT_CONTEXT_REGEX + rb\"[ \\t]*[#$][ \\t]*[^\\r\\n]+(?:\\r?\\n)?\"\n\n    def _credential_rejected(self):\n        # A rejected interaction cannot establish the newly selected\n        # bootstrap password.  Do not activate it on a later unrelated\n        # acceptance or prompt.\n        self._pending_bootstrap_activation = False\n        if not self._initial_login_complete and self._blank_fallback_available:\n            self._send_blank_password = True\n            return\n        if (\n            self._allow_credential_recovery\n            and self._recovery_credentials is not None\n            and not self._recovery_attempted\n        ):\n            self._recovery_attempted = True\n            self._use_recovery_credentials = True\n            self._logger.warning(\n                \"Credentials were rejected; retrying with the previously accepted credentials\"\n            )\n            return\n        raise RuntimeError(\"Credential rejected\")\n\n    def _respond(self, state, response):\n        \"\"\"Write an interactive response to the CLI.\"\"\"\n        if isinstance(response, str):\n            response = response.encode()\n        self._logger.log(\n            TRACE_LEVEL,\n            \"Responding to CLI state %s with '%s'\",\n            state.name,\n            response,\n        )\n        self._terminal.write(bytes(response) + b\"\\r\")",
        "lineStart": 56,
        "lineEnd": 331,
        "totalLines": 331,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716545125,
      "end": 1793716545130
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/terminal.py",
  "offset": 65
}

Output

<path>/source/head/fortinet/common/terminal.py</path>
<type>file</type>
<content>
65:     def discard(self, value=None):
66:         discard_value = self.value if value is None else bytes(value)
67:         if not discard_value:
68:             return
69:         if self._discard_callback:
70:             self._discard_callback(discard_value)
71:         self.discarded = True
72: 
73: 
74: class _ByteQueue:
75:     def __init__(self, max_size):
76:         self._max_size = max_size
77:         self._chunks = deque()
78:         self._size = 0
79:         self._closed = False
80:         self._error = None
81:         self._condition = threading.Condition()
82: 
83:     def put(self, data):
84:         offset = 0
85:         while offset < len(data):
86:             with self._condition:
87:                 while not self._closed and self._error is None and self._size >= self._max_size:
88:                     self._condition.wait()
89:                 if self._closed or self._error is not None:
90:                     return
91: 
92:                 available = self._max_size - self._size
93:                 chunk = bytes(data[offset:offset + available])
94:                 self._chunks.append(chunk)
95:                 self._size += len(chunk)
96:                 offset += len(chunk)
97:                 self._condition.notify_all()
98: 
99:     def get(self, timeout=None):
100:         deadline = None if timeout is None else time.monotonic() + timeout
101:         with self._condition:
102:             while not self._chunks and not self._closed and self._error is None:
103:                 if deadline is None:
104:                     self._condition.wait()
105:                     continue
106: 
107:                 remaining = deadline - time.monotonic()
108:                 if remaining <= 0:
109:                     return b""
110:                 self._condition.wait(remaining)
111: 
112:             if self._error is not None:
113:                 raise self._error
114:             if not self._chunks:
115:                 return b""
116: 
117:             data = b"".join(self._chunks)
118:             self._chunks.clear()
119:             self._size = 0
120:             self._condition.notify_all()
121:             return data
122: 
123:     def get_one(self, timeout=None):
124:         deadline = None if timeout is None else time.monotonic() + timeout
125:         with self._condition:
126:             while not self._chunks and not self._closed and self._error is None:
127:                 if deadline is None:
128:                     self._condition.wait()
129:                     continue
130: 
131:                 remaining = deadline - time.monotonic()
132:                 if remaining <= 0:
133:                     return b""
134:                 self._condition.wait(remaining)
135: 
136:             if self._error is not None:
137:                 raise self._error
138:             if not self._chunks:
139:                 return b""
140: 
141:             data = self._chunks.popleft()
142:             self._size -= len(data)
143:             self._condition.notify_all()
144:             return data
145: 
146:     def close(self):
147:         with self._condition:
148:             self._closed = True
149:             self._condition.notify_all()
150: 
151:     def fail(self, error):
152:         with self._condition:
153:             self._error = error
154:             self._condition.notify_all()
155: 
156: 
157: class Terminal:
158:     """Buffered access to the FortiOS serial console."""
159: 
160:     def __init__(self, connection, logger, default_wait="#"):
161:         self._connection = connection
162:         self._logger = logger
163:         self._default_wait = default_wait
164:         self._buffer = bytearray()
165:         self._buffer_limit = terminal_buffer_limit_bytes()
166:         self._read_queue = _ByteQueue(self._buffer_limit)
167:         self._write_queue = _ByteQueue(self._buffer_limit)
168:         self._reader_lock = threading.Lock()
169:         self._stop_reader = None
170:         self._reader = None
171:         self._writer_lock = threading.Lock()
172:         self._writer = None
173:         self._output_suppression_depth = 0
174:         self._output_suppression_context = None
175: 
176:     def write(self, data):
177:         if isinstance(data, str):
178:             data = data.encode()
179:         self._ensure_writer()
180:         self._write_queue.put(data)
181: 
182:     def wait_write(
183:         self,
184:         cmd,
185:         wait="__defaultpattern__",
186:         clean_buffer=False,
187:         hold="",
188:         timeout=None,
189:     ):
190:         if wait:
191:             if wait == "__defaultpattern__":
192:                 wait = self._default_wait
193:             self._logger.info(f"waiting for '{wait}' on serial console")
194:             pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)
195:             _, match, output = self.expect([pattern], timeout)
196: 
197:             while match and hold and hold.encode() in output:
198:                 self._logger.info(
199:                     f"Holding pattern '{hold}' detected, retrying in 10s..."
200:                 )
201:                 self.write(b"\r")
202:                 time.sleep(10)
203:                 _, match, output = self.expect([pattern], timeout)
204: 
205:             if not match:
206:                 self._logger.info(
207:                     f"timed out waiting for '{wait}' on serial console"
208:                 )
209: 
210:         if clean_buffer:
211:             self._buffer.clear()
212: 
213:         self._logger.debug(f"writing to serial console: '{cmd}'")
214:         self.write(f"{cmd}\r")
215: 
216:     def expect(self, regex_list, timeout=None):
217:         """Read until a pattern matches, retaining unmatched data across calls.
218: 
219:         The match ending earliest in the buffered stream wins. Data through that
220:         match is returned and discarded; data after it remains buffered.
221:         On timeout, the entire unmatched buffer is returned for inspection and
222:         stays buffered unless the caller explicitly discards it.
223:         """
224:         self._ensure_reader()
225:         deadline = None if timeout is None else time.monotonic() + timeout
226:         received_new_data = False
227:         result = self._match(regex_list)
228: 
229:         while result is None:
230:             remaining = None if deadline is None else deadline - time.monotonic()
231:             if remaining is not None and remaining <= 0:
232:                 return -1, None, Data(
233:                     self._buffer,
234:                     self._discard_prefix,
235:                     received_new_data=received_new_data,
236:                 )
237: 
238:             data = self._read_queue.get(remaining)
239:             if data:
240:                 self._buffer.extend(data)
241:                 self._enforce_buffer_limit()
242:                 received_new_data = True
243:                 if (
244:                     get_env(RAW_SERIAL_LOG_ENV, "").lower() in ("1", "true", "yes")
245:                     and self._output_suppression_depth == 0
246:                 ):
247:                     self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")
248:                 result = self._match(regex_list)
249:                 continue
250: 
251:             if deadline is not None and time.monotonic() >= deadline:
252:                 return -1, None, Data(
253:                     self._buffer,
254:                     self._discard_prefix,
255:                     received_new_data=received_new_data,
256:                 )
257: 
258:         index, match = result
259:         consumed = bytes(self._buffer[:match.end()])
260:         stable_match = re.search(regex_list[index], consumed)
261:         del self._buffer[:match.end()]
262:         return index, stable_match, Data(consumed)
263: 
264:     def _discard_prefix(self, data):
265:         """Discard bytes that a caller has consumed from the retained buffer."""
266:         if not data:
267:             return
268:         if not self._buffer.startswith(data):
269:             message = "Refusing to discard non-prefix terminal output"
270:             if self._logger.isEnabledFor(TRACE_LEVEL):
271:                 message += f": data={data!r}; buffer={self._buffer!r}"
272:             self._logger.warning(message)
273:             return
274:         del self._buffer[:len(data)]
275: 
276:     def _enforce_buffer_limit(self):
277:         if len(self._buffer) <= self._buffer_limit:
278:             return
279: 
280:         self._logger.error(
281:             "Terminal buffer exceeded %s bytes. Tail: %r",
282:             self._buffer_limit,
283:             bytes(self._buffer[-512:]),
284:         )
285:         raise RuntimeError(
286:             f"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed"
287:         )
288: 
289:     def _ensure_reader(self):
290:         with self._reader_lock:
291:             if self._reader is not None and self._reader.is_alive():
292:                 return
293: 
294:             self._read_queue = _ByteQueue(self._buffer_limit)
295:             self._stop_reader = threading.Event()
296:             self._reader = threading.Thread(
297:                 target=self._read_forever,
298:                 args=(self._stop_reader, self._read_queue),
299:                 name="fortios-terminal-reader",
300:             )
301:             self._reader.daemon = True
302:             self._reader.start()
303: 
304:     def _read_forever(self, stop_reader, read_queue):
305:         while not stop_reader.is_set():
306:             try:
307:                 data = self._connection.read_very_eager()
308:             except Exception as error:
309:                 if not stop_reader.is_set():
310:                     self._logger.exception("Terminal reader failed")
311:                     read_queue.fail(error)
312:                 return
313: 
314:             if data:
315:                 read_queue.put(data)
316:             else:
317:                 stop_reader.wait(READ_POLL_SECONDS)
318: 
319:     def _ensure_writer(self):
320:         with self._writer_lock:
321:             if self._writer is not None and self._writer.is_alive():
322:                 return
323: 
324:             self._write_queue = _ByteQueue(self._buffer_limit)
325:             self._writer = threading.Thread(
326:                 target=self._write_forever,
327:                 args=(self._write_queue,),
328:                 name="fortios-terminal-writer",
329:             )
330:             self._writer.daemon = True
331:             self._writer.start()
332: 
333:     def _write_forever(self, write_queue):
334:         while True:
335:             try:
336:                 data = write_queue.get_one()
337:             except Exception:
338:                 self._logger.exception("Terminal writer failed")
339:                 return
340: 
341:             if not data:
342:                 return
343: 
344:             try:
345:                 self._connection.write(data)
346:             except Exception:
347:                 self._logger.exception("Terminal writer failed")
348:                 return
349: 
350:     def close(self):
351:         with self._reader_lock:
352:             reader = self._reader
353:             stop_reader = self._stop_reader
354:             read_queue = self._read_queue
355:             self._reader = None
356:             self._stop_reader = None
357: 
358:         with self._writer_lock:
359:             writer = self._writer
360:             write_queue = self._write_queue
361:             self._writer = None
362: 
363:         if stop_reader is not None:
364:             stop_reader.set()
365:         read_queue.close()
366:         write_queue.close()
367:         if writer is not None:
368:             writer.join(1)
369:         self._buffer.clear()
370:         self._connection.close()
371:         if reader is not None:
372:             reader.join(1)
373: 
374:     @contextmanager
375:     def suppress_output(self):
376:         if self._output_suppression_depth == 0:
377:             self._output_suppression_context = self._connection.suppress_output()
378:             self._output_suppression_context.__enter__()
379:         self._output_suppression_depth += 1
380:         try:
381:             yield
382:         finally:
383:             self._output_suppression_depth -= 1
384:             if self._output_suppression_depth == 0:
385:                 try:
386:                     self._output_suppression_context.__exit__(None, None, None)
387:                 finally:
388:                     self._output_suppression_context = None
389: 
390:     def _match(self, regex_list):
391:         winner = None
392:         for index, pattern in enumerate(regex_list):
393:             match = re.search(pattern, self._buffer)
394:             if match is None:
395:                 continue
396:             if winner is None or match.end() < winner[1].end():
397:                 winner = index, match
398:         return winner

(End of file - total 398 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d666a5001kGGps6Y73mm0hE",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d645de0015j2Xa816gxTk2E",
  "callID": "call_82379fa8d9494cbeaf4b1fc3",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/terminal.py",
      "offset": 65
    },
    "output": "<path>/source/head/fortinet/common/terminal.py</path>\n<type>file</type>\n<content>\n65:     def discard(self, value=None):\n66:         discard_value = self.value if value is None else bytes(value)\n67:         if not discard_value:\n68:             return\n69:         if self._discard_callback:\n70:             self._discard_callback(discard_value)\n71:         self.discarded = True\n72: \n73: \n74: class _ByteQueue:\n75:     def __init__(self, max_size):\n76:         self._max_size = max_size\n77:         self._chunks = deque()\n78:         self._size = 0\n79:         self._closed = False\n80:         self._error = None\n81:         self._condition = threading.Condition()\n82: \n83:     def put(self, data):\n84:         offset = 0\n85:         while offset < len(data):\n86:             with self._condition:\n87:                 while not self._closed and self._error is None and self._size >= self._max_size:\n88:                     self._condition.wait()\n89:                 if self._closed or self._error is not None:\n90:                     return\n91: \n92:                 available = self._max_size - self._size\n93:                 chunk = bytes(data[offset:offset + available])\n94:                 self._chunks.append(chunk)\n95:                 self._size += len(chunk)\n96:                 offset += len(chunk)\n97:                 self._condition.notify_all()\n98: \n99:     def get(self, timeout=None):\n100:         deadline = None if timeout is None else time.monotonic() + timeout\n101:         with self._condition:\n102:             while not self._chunks and not self._closed and self._error is None:\n103:                 if deadline is None:\n104:                     self._condition.wait()\n105:                     continue\n106: \n107:                 remaining = deadline - time.monotonic()\n108:                 if remaining <= 0:\n109:                     return b\"\"\n110:                 self._condition.wait(remaining)\n111: \n112:             if self._error is not None:\n113:                 raise self._error\n114:             if not self._chunks:\n115:                 return b\"\"\n116: \n117:             data = b\"\".join(self._chunks)\n118:             self._chunks.clear()\n119:             self._size = 0\n120:             self._condition.notify_all()\n121:             return data\n122: \n123:     def get_one(self, timeout=None):\n124:         deadline = None if timeout is None else time.monotonic() + timeout\n125:         with self._condition:\n126:             while not self._chunks and not self._closed and self._error is None:\n127:                 if deadline is None:\n128:                     self._condition.wait()\n129:                     continue\n130: \n131:                 remaining = deadline - time.monotonic()\n132:                 if remaining <= 0:\n133:                     return b\"\"\n134:                 self._condition.wait(remaining)\n135: \n136:             if self._error is not None:\n137:                 raise self._error\n138:             if not self._chunks:\n139:                 return b\"\"\n140: \n141:             data = self._chunks.popleft()\n142:             self._size -= len(data)\n143:             self._condition.notify_all()\n144:             return data\n145: \n146:     def close(self):\n147:         with self._condition:\n148:             self._closed = True\n149:             self._condition.notify_all()\n150: \n151:     def fail(self, error):\n152:         with self._condition:\n153:             self._error = error\n154:             self._condition.notify_all()\n155: \n156: \n157: class Terminal:\n158:     \"\"\"Buffered access to the FortiOS serial console.\"\"\"\n159: \n160:     def __init__(self, connection, logger, default_wait=\"#\"):\n161:         self._connection = connection\n162:         self._logger = logger\n163:         self._default_wait = default_wait\n164:         self._buffer = bytearray()\n165:         self._buffer_limit = terminal_buffer_limit_bytes()\n166:         self._read_queue = _ByteQueue(self._buffer_limit)\n167:         self._write_queue = _ByteQueue(self._buffer_limit)\n168:         self._reader_lock = threading.Lock()\n169:         self._stop_reader = None\n170:         self._reader = None\n171:         self._writer_lock = threading.Lock()\n172:         self._writer = None\n173:         self._output_suppression_depth = 0\n174:         self._output_suppression_context = None\n175: \n176:     def write(self, data):\n177:         if isinstance(data, str):\n178:             data = data.encode()\n179:         self._ensure_writer()\n180:         self._write_queue.put(data)\n181: \n182:     def wait_write(\n183:         self,\n184:         cmd,\n185:         wait=\"__defaultpattern__\",\n186:         clean_buffer=False,\n187:         hold=\"\",\n188:         timeout=None,\n189:     ):\n190:         if wait:\n191:             if wait == \"__defaultpattern__\":\n192:                 wait = self._default_wait\n193:             self._logger.info(f\"waiting for '{wait}' on serial console\")\n194:             pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)\n195:             _, match, output = self.expect([pattern], timeout)\n196: \n197:             while match and hold and hold.encode() in output:\n198:                 self._logger.info(\n199:                     f\"Holding pattern '{hold}' detected, retrying in 10s...\"\n200:                 )\n201:                 self.write(b\"\\r\")\n202:                 time.sleep(10)\n203:                 _, match, output = self.expect([pattern], timeout)\n204: \n205:             if not match:\n206:                 self._logger.info(\n207:                     f\"timed out waiting for '{wait}' on serial console\"\n208:                 )\n209: \n210:         if clean_buffer:\n211:             self._buffer.clear()\n212: \n213:         self._logger.debug(f\"writing to serial console: '{cmd}'\")\n214:         self.write(f\"{cmd}\\r\")\n215: \n216:     def expect(self, regex_list, timeout=None):\n217:         \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n218: \n219:         The match ending earliest in the buffered stream wins. Data through that\n220:         match is returned and discarded; data after it remains buffered.\n221:         On timeout, the entire unmatched buffer is returned for inspection and\n222:         stays buffered unless the caller explicitly discards it.\n223:         \"\"\"\n224:         self._ensure_reader()\n225:         deadline = None if timeout is None else time.monotonic() + timeout\n226:         received_new_data = False\n227:         result = self._match(regex_list)\n228: \n229:         while result is None:\n230:             remaining = None if deadline is None else deadline - time.monotonic()\n231:             if remaining is not None and remaining <= 0:\n232:                 return -1, None, Data(\n233:                     self._buffer,\n234:                     self._discard_prefix,\n235:                     received_new_data=received_new_data,\n236:                 )\n237: \n238:             data = self._read_queue.get(remaining)\n239:             if data:\n240:                 self._buffer.extend(data)\n241:                 self._enforce_buffer_limit()\n242:                 received_new_data = True\n243:                 if (\n244:                     get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n245:                     and self._output_suppression_depth == 0\n246:                 ):\n247:                     self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n248:                 result = self._match(regex_list)\n249:                 continue\n250: \n251:             if deadline is not None and time.monotonic() >= deadline:\n252:                 return -1, None, Data(\n253:                     self._buffer,\n254:                     self._discard_prefix,\n255:                     received_new_data=received_new_data,\n256:                 )\n257: \n258:         index, match = result\n259:         consumed = bytes(self._buffer[:match.end()])\n260:         stable_match = re.search(regex_list[index], consumed)\n261:         del self._buffer[:match.end()]\n262:         return index, stable_match, Data(consumed)\n263: \n264:     def _discard_prefix(self, data):\n265:         \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n266:         if not data:\n267:             return\n268:         if not self._buffer.startswith(data):\n269:             message = \"Refusing to discard non-prefix terminal output\"\n270:             if self._logger.isEnabledFor(TRACE_LEVEL):\n271:                 message += f\": data={data!r}; buffer={self._buffer!r}\"\n272:             self._logger.warning(message)\n273:             return\n274:         del self._buffer[:len(data)]\n275: \n276:     def _enforce_buffer_limit(self):\n277:         if len(self._buffer) <= self._buffer_limit:\n278:             return\n279: \n280:         self._logger.error(\n281:             \"Terminal buffer exceeded %s bytes. Tail: %r\",\n282:             self._buffer_limit,\n283:             bytes(self._buffer[-512:]),\n284:         )\n285:         raise RuntimeError(\n286:             f\"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed\"\n287:         )\n288: \n289:     def _ensure_reader(self):\n290:         with self._reader_lock:\n291:             if self._reader is not None and self._reader.is_alive():\n292:                 return\n293: \n294:             self._read_queue = _ByteQueue(self._buffer_limit)\n295:             self._stop_reader = threading.Event()\n296:             self._reader = threading.Thread(\n297:                 target=self._read_forever,\n298:                 args=(self._stop_reader, self._read_queue),\n299:                 name=\"fortios-terminal-reader\",\n300:             )\n301:             self._reader.daemon = True\n302:             self._reader.start()\n303: \n304:     def _read_forever(self, stop_reader, read_queue):\n305:         while not stop_reader.is_set():\n306:             try:\n307:                 data = self._connection.read_very_eager()\n308:             except Exception as error:\n309:                 if not stop_reader.is_set():\n310:                     self._logger.exception(\"Terminal reader failed\")\n311:                     read_queue.fail(error)\n312:                 return\n313: \n314:             if data:\n315:                 read_queue.put(data)\n316:             else:\n317:                 stop_reader.wait(READ_POLL_SECONDS)\n318: \n319:     def _ensure_writer(self):\n320:         with self._writer_lock:\n321:             if self._writer is not None and self._writer.is_alive():\n322:                 return\n323: \n324:             self._write_queue = _ByteQueue(self._buffer_limit)\n325:             self._writer = threading.Thread(\n326:                 target=self._write_forever,\n327:                 args=(self._write_queue,),\n328:                 name=\"fortios-terminal-writer\",\n329:             )\n330:             self._writer.daemon = True\n331:             self._writer.start()\n332: \n333:     def _write_forever(self, write_queue):\n334:         while True:\n335:             try:\n336:                 data = write_queue.get_one()\n337:             except Exception:\n338:                 self._logger.exception(\"Terminal writer failed\")\n339:                 return\n340: \n341:             if not data:\n342:                 return\n343: \n344:             try:\n345:                 self._connection.write(data)\n346:             except Exception:\n347:                 self._logger.exception(\"Terminal writer failed\")\n348:                 return\n349: \n350:     def close(self):\n351:         with self._reader_lock:\n352:             reader = self._reader\n353:             stop_reader = self._stop_reader\n354:             read_queue = self._read_queue\n355:             self._reader = None\n356:             self._stop_reader = None\n357: \n358:         with self._writer_lock:\n359:             writer = self._writer\n360:             write_queue = self._write_queue\n361:             self._writer = None\n362: \n363:         if stop_reader is not None:\n364:             stop_reader.set()\n365:         read_queue.close()\n366:         write_queue.close()\n367:         if writer is not None:\n368:             writer.join(1)\n369:         self._buffer.clear()\n370:         self._connection.close()\n371:         if reader is not None:\n372:             reader.join(1)\n373: \n374:     @contextmanager\n375:     def suppress_output(self):\n376:         if self._output_suppression_depth == 0:\n377:             self._output_suppression_context = self._connection.suppress_output()\n378:             self._output_suppression_context.__enter__()\n379:         self._output_suppression_depth += 1\n380:         try:\n381:             yield\n382:         finally:\n383:             self._output_suppression_depth -= 1\n384:             if self._output_suppression_depth == 0:\n385:                 try:\n386:                     self._output_suppression_context.__exit__(None, None, None)\n387:                 finally:\n388:                     self._output_suppression_context = None\n389: \n390:     def _match(self, regex_list):\n391:         winner = None\n392:         for index, pattern in enumerate(regex_list):\n393:             match = re.search(pattern, self._buffer)\n394:             if match is None:\n395:                 continue\n396:             if winner is None or match.end() < winner[1].end():\n397:                 winner = index, match\n398:         return winner\n\n(End of file - total 398 lines)\n</content>",
    "title": "source/head/fortinet/common/terminal.py",
    "metadata": {
      "preview": "    def discard(self, value=None):\n        discard_value = self.value if value is None else bytes(value)\n        if not discard_value:\n            return\n        if self._discard_callback:\n            self._discard_callback(discard_value)\n        self.discarded = True\n\n\nclass _ByteQueue:\n    def __init__(self, max_size):\n        self._max_size = max_size\n        self._chunks = deque()\n        self._size = 0\n        self._closed = False\n        self._error = None\n        self._condition = threading.Condition()\n\n    def put(self, data):\n        offset = 0",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/terminal.py",
        "text": "    def discard(self, value=None):\n        discard_value = self.value if value is None else bytes(value)\n        if not discard_value:\n            return\n        if self._discard_callback:\n            self._discard_callback(discard_value)\n        self.discarded = True\n\n\nclass _ByteQueue:\n    def __init__(self, max_size):\n        self._max_size = max_size\n        self._chunks = deque()\n        self._size = 0\n        self._closed = False\n        self._error = None\n        self._condition = threading.Condition()\n\n    def put(self, data):\n        offset = 0\n        while offset < len(data):\n            with self._condition:\n                while not self._closed and self._error is None and self._size >= self._max_size:\n                    self._condition.wait()\n                if self._closed or self._error is not None:\n                    return\n\n                available = self._max_size - self._size\n                chunk = bytes(data[offset:offset + available])\n                self._chunks.append(chunk)\n                self._size += len(chunk)\n                offset += len(chunk)\n                self._condition.notify_all()\n\n    def get(self, timeout=None):\n        deadline = None if timeout is None else time.monotonic() + timeout\n        with self._condition:\n            while not self._chunks and not self._closed and self._error is None:\n                if deadline is None:\n                    self._condition.wait()\n                    continue\n\n                remaining = deadline - time.monotonic()\n                if remaining <= 0:\n                    return b\"\"\n                self._condition.wait(remaining)\n\n            if self._error is not None:\n                raise self._error\n            if not self._chunks:\n                return b\"\"\n\n            data = b\"\".join(self._chunks)\n            self._chunks.clear()\n            self._size = 0\n            self._condition.notify_all()\n            return data\n\n    def get_one(self, timeout=None):\n        deadline = None if timeout is None else time.monotonic() + timeout\n        with self._condition:\n            while not self._chunks and not self._closed and self._error is None:\n                if deadline is None:\n                    self._condition.wait()\n                    continue\n\n                remaining = deadline - time.monotonic()\n                if remaining <= 0:\n                    return b\"\"\n                self._condition.wait(remaining)\n\n            if self._error is not None:\n                raise self._error\n            if not self._chunks:\n                return b\"\"\n\n            data = self._chunks.popleft()\n            self._size -= len(data)\n            self._condition.notify_all()\n            return data\n\n    def close(self):\n        with self._condition:\n            self._closed = True\n            self._condition.notify_all()\n\n    def fail(self, error):\n        with self._condition:\n            self._error = error\n            self._condition.notify_all()\n\n\nclass Terminal:\n    \"\"\"Buffered access to the FortiOS serial console.\"\"\"\n\n    def __init__(self, connection, logger, default_wait=\"#\"):\n        self._connection = connection\n        self._logger = logger\n        self._default_wait = default_wait\n        self._buffer = bytearray()\n        self._buffer_limit = terminal_buffer_limit_bytes()\n        self._read_queue = _ByteQueue(self._buffer_limit)\n        self._write_queue = _ByteQueue(self._buffer_limit)\n        self._reader_lock = threading.Lock()\n        self._stop_reader = None\n        self._reader = None\n        self._writer_lock = threading.Lock()\n        self._writer = None\n        self._output_suppression_depth = 0\n        self._output_suppression_context = None\n\n    def write(self, data):\n        if isinstance(data, str):\n            data = data.encode()\n        self._ensure_writer()\n        self._write_queue.put(data)\n\n    def wait_write(\n        self,\n        cmd,\n        wait=\"__defaultpattern__\",\n        clean_buffer=False,\n        hold=\"\",\n        timeout=None,\n    ):\n        if wait:\n            if wait == \"__defaultpattern__\":\n                wait = self._default_wait\n            self._logger.info(f\"waiting for '{wait}' on serial console\")\n            pattern = re.escape(wait.encode() if isinstance(wait, str) else wait)\n            _, match, output = self.expect([pattern], timeout)\n\n            while match and hold and hold.encode() in output:\n                self._logger.info(\n                    f\"Holding pattern '{hold}' detected, retrying in 10s...\"\n                )\n                self.write(b\"\\r\")\n                time.sleep(10)\n                _, match, output = self.expect([pattern], timeout)\n\n            if not match:\n                self._logger.info(\n                    f\"timed out waiting for '{wait}' on serial console\"\n                )\n\n        if clean_buffer:\n            self._buffer.clear()\n\n        self._logger.debug(f\"writing to serial console: '{cmd}'\")\n        self.write(f\"{cmd}\\r\")\n\n    def expect(self, regex_list, timeout=None):\n        \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n\n        The match ending earliest in the buffered stream wins. Data through that\n        match is returned and discarded; data after it remains buffered.\n        On timeout, the entire unmatched buffer is returned for inspection and\n        stays buffered unless the caller explicitly discards it.\n        \"\"\"\n        self._ensure_reader()\n        deadline = None if timeout is None else time.monotonic() + timeout\n        received_new_data = False\n        result = self._match(regex_list)\n\n        while result is None:\n            remaining = None if deadline is None else deadline - time.monotonic()\n            if remaining is not None and remaining <= 0:\n                return -1, None, Data(\n                    self._buffer,\n                    self._discard_prefix,\n                    received_new_data=received_new_data,\n                )\n\n            data = self._read_queue.get(remaining)\n            if data:\n                self._buffer.extend(data)\n                self._enforce_buffer_limit()\n                received_new_data = True\n                if (\n                    get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n                    and self._output_suppression_depth == 0\n                ):\n                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n                result = self._match(regex_list)\n                continue\n\n            if deadline is not None and time.monotonic() >= deadline:\n                return -1, None, Data(\n                    self._buffer,\n                    self._discard_prefix,\n                    received_new_data=received_new_data,\n                )\n\n        index, match = result\n        consumed = bytes(self._buffer[:match.end()])\n        stable_match = re.search(regex_list[index], consumed)\n        del self._buffer[:match.end()]\n        return index, stable_match, Data(consumed)\n\n    def _discard_prefix(self, data):\n        \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n        if not data:\n            return\n        if not self._buffer.startswith(data):\n            message = \"Refusing to discard non-prefix terminal output\"\n            if self._logger.isEnabledFor(TRACE_LEVEL):\n                message += f\": data={data!r}; buffer={self._buffer!r}\"\n            self._logger.warning(message)\n            return\n        del self._buffer[:len(data)]\n\n    def _enforce_buffer_limit(self):\n        if len(self._buffer) <= self._buffer_limit:\n            return\n\n        self._logger.error(\n            \"Terminal buffer exceeded %s bytes. Tail: %r\",\n            self._buffer_limit,\n            bytes(self._buffer[-512:]),\n        )\n        raise RuntimeError(\n            f\"Terminal buffer exceeded {self._buffer_limit} bytes without being consumed\"\n        )\n\n    def _ensure_reader(self):\n        with self._reader_lock:\n            if self._reader is not None and self._reader.is_alive():\n                return\n\n            self._read_queue = _ByteQueue(self._buffer_limit)\n            self._stop_reader = threading.Event()\n            self._reader = threading.Thread(\n                target=self._read_forever,\n                args=(self._stop_reader, self._read_queue),\n                name=\"fortios-terminal-reader\",\n            )\n            self._reader.daemon = True\n            self._reader.start()\n\n    def _read_forever(self, stop_reader, read_queue):\n        while not stop_reader.is_set():\n            try:\n                data = self._connection.read_very_eager()\n            except Exception as error:\n                if not stop_reader.is_set():\n                    self._logger.exception(\"Terminal reader failed\")\n                    read_queue.fail(error)\n                return\n\n            if data:\n                read_queue.put(data)\n            else:\n                stop_reader.wait(READ_POLL_SECONDS)\n\n    def _ensure_writer(self):\n        with self._writer_lock:\n            if self._writer is not None and self._writer.is_alive():\n                return\n\n            self._write_queue = _ByteQueue(self._buffer_limit)\n            self._writer = threading.Thread(\n                target=self._write_forever,\n                args=(self._write_queue,),\n                name=\"fortios-terminal-writer\",\n            )\n            self._writer.daemon = True\n            self._writer.start()\n\n    def _write_forever(self, write_queue):\n        while True:\n            try:\n                data = write_queue.get_one()\n            except Exception:\n                self._logger.exception(\"Terminal writer failed\")\n                return\n\n            if not data:\n                return\n\n            try:\n                self._connection.write(data)\n            except Exception:\n                self._logger.exception(\"Terminal writer failed\")\n                return\n\n    def close(self):\n        with self._reader_lock:\n            reader = self._reader\n            stop_reader = self._stop_reader\n            read_queue = self._read_queue\n            self._reader = None\n            self._stop_reader = None\n\n        with self._writer_lock:\n            writer = self._writer\n            write_queue = self._write_queue\n            self._writer = None\n\n        if stop_reader is not None:\n            stop_reader.set()\n        read_queue.close()\n        write_queue.close()\n        if writer is not None:\n            writer.join(1)\n        self._buffer.clear()\n        self._connection.close()\n        if reader is not None:\n            reader.join(1)\n\n    @contextmanager\n    def suppress_output(self):\n        if self._output_suppression_depth == 0:\n            self._output_suppression_context = self._connection.suppress_output()\n            self._output_suppression_context.__enter__()\n        self._output_suppression_depth += 1\n        try:\n            yield\n        finally:\n            self._output_suppression_depth -= 1\n            if self._output_suppression_depth == 0:\n                try:\n                    self._output_suppression_context.__exit__(None, None, None)\n                finally:\n                    self._output_suppression_context = None\n\n    def _match(self, regex_list):\n        winner = None\n        for index, pattern in enumerate(regex_list):\n            match = re.search(pattern, self._buffer)\n            if match is None:\n                continue\n            if winner is None or match.end() < winner[1].end():\n                winner = index, match\n        return winner",
        "lineStart": 65,
        "lineEnd": 398,
        "totalLines": 398,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716545193,
      "end": 1793716545199
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/cli_commands.py",
  "offset": 45
}

Output

<path>/source/head/fortinet/common/cli_commands.py</path>
<type>file</type>
<content>
45:         object.__setattr__(self, "continuation", continuation)
46:         if context_loss is None:
47:             # Commands that must not replay after logout must not replay after
48:             # an unexpected scope exit either. Features can override this policy.
49:             context_loss = (
50:                 ContextLossAction.RESTART_BLOCK
51:                 if session_loss == SessionLossAction.RESTART_BLOCK
52:                 else ContextLossAction.FAIL
53:             )
54:         object.__setattr__(self, "context_loss", context_loss)
55:         self.__post_init__()
56: 
57:     def __post_init__(self):
58:         if "\r" in self.line or "\n" in self.line:
59:             raise ValueError("CLI commands must contain exactly one line")
60: 
61:     @property
62:     def closes_scope(self):
63:         return not self.continuation and self.line.strip().lower() in {"next", "end"}
64: 
65: 
66: @dataclass
67: class CommandAttempt:
68:     spec: CommandSpec
69:     number: int
70:     session_epoch: int
71:     output: bytearray = field(default_factory=bytearray)
72:     prompt_context_before: tuple | None = None
73:     prompt_context_after: tuple | None = None
74:     block_index: int | None = None
75:     retry_count: int = 0
76: 
77:     def on_output(self, output):
78:         if not (self.spec.capture_output or self.spec.closes_scope):
79:             return False
80:         data = bytes(output)
81:         self.output.extend(data)
82:         output.discard(data)
83:         return True
84: 
85: 
86: class Scope:
87:     def __init__(self, value, children=()):
88:         self.value = value
89:         self.children = list(children)
90: 
91:     @property
92:     def open_line(self):
93:         raise NotImplementedError
94: 
95:     @property
96:     def close_line(self):
97:         raise NotImplementedError
98: 
99:     def flatten(self):
100:         commands = flatten_commands(self.open_line)
101:         for child in self.children:
102:             commands.extend(flatten_commands(child))
103:         commands.append(CommandSpec(self.close_line))
104:         return commands
105: 
106: 
107: class ConfigBlock(Scope):
108:     @property
109:     def open_line(self):
110:         return f"config {self.value}"
111: 
112:     @property
113:     def close_line(self):
114:         return "end"
115: 
116: 
117: class EditBlock(Scope):
118:     @property
119:     def open_line(self):
120:         return f"edit {self.value}"
121: 
122:     @property
123:     def close_line(self):
124:         return "next"
125: 
126: 
127: class SetValue:
128:     """A quoted ``set`` command supporting FortiOS continuation prompts."""
129: 
130:     def __init__(self, field, value, fail_on_error=True, validate_prompt=True):
131:         self.field = field
132:         self.value = value
133:         self.fail_on_error = fail_on_error
134:         self.validate_prompt = validate_prompt
135: 
136:     def flatten(self):
137:         lines = str(self.value).strip().splitlines() or [""]
138:         lines[0] = f'set {self.field} "{lines[0]}'
139:         lines[-1] += '"'
140:         return _flatten_quoted_lines(
141:             lines, fail_on_error=self.fail_on_error,
142:             validate_prompt=self.validate_prompt,
143:         )
144: 
145: 
146: def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):
147:     """Send a logical command one line per continuation prompt, without re-quoting."""
148:     commands = []
149:     for index, line in enumerate(lines):
150:         last_line = index == len(lines) - 1
151:         expected = (
152:             FOSCliState.CMD_PROMPT if last_line
153:             else FOSCliState.MULTILINE_PROMPT
154:         )
155:         completion_states = ()
156:         if len(lines) > 1:
157:             completion_states = (
158:                 (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)
159:                 if last_line else
160:                 (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
161:             )
162:         commands.append(CommandSpec(
163:             line,
164:             completion_states=completion_states,
165:             capture_output=True,
166:             expected_completion_state=expected if validate_prompt else None,
167:             fail_on_error=fail_on_error,
168:             continuation=index > 0,
169:         ))
170:     return commands
171: 
172: 
173: class CommandSequence:
174:     """An unscoped workflow container; it does not emit CLI framing."""
175: 
176:     def __init__(self, name, children=()):
177:         self.name = name
178:         self.children = list(children)
179: 
180:     def flatten(self):
181:         commands = []
182:         for child in self.children:
183:             commands.extend(flatten_commands(child))
184:         return commands
185: 
186: 
187: def flatten_commands(value):
188:     """Flatten command containers and wrap plain CLI lines with defaults."""
189:     if isinstance(value, str):
190:         if "\n" in value:
191:             return _flatten_quoted_lines(value.split("\n"))
192:         return [CommandSpec(value)]
193:     if isinstance(value, CommandSpec):
194:         return [value]
195:     if isinstance(value, (Scope, CommandSequence, SetValue)):
196:         return value.flatten()
197:     raise TypeError(
198:         "Commands must be strings, CommandSpec instances, or command containers"
199:     )
200: 
201: 
202: @dataclass(frozen=True)
203: class CleanupAction:
204:     name: str
205:     block: object
206:     on_completion: bool = True
207:     on_interruption: bool = True

(End of file - total 207 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d666ea001WnLad8op4ZtSlp",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d645de0015j2Xa816gxTk2E",
  "callID": "call_ac7c2f9814f34416bf33483e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/cli_commands.py",
      "offset": 45
    },
    "output": "<path>/source/head/fortinet/common/cli_commands.py</path>\n<type>file</type>\n<content>\n45:         object.__setattr__(self, \"continuation\", continuation)\n46:         if context_loss is None:\n47:             # Commands that must not replay after logout must not replay after\n48:             # an unexpected scope exit either. Features can override this policy.\n49:             context_loss = (\n50:                 ContextLossAction.RESTART_BLOCK\n51:                 if session_loss == SessionLossAction.RESTART_BLOCK\n52:                 else ContextLossAction.FAIL\n53:             )\n54:         object.__setattr__(self, \"context_loss\", context_loss)\n55:         self.__post_init__()\n56: \n57:     def __post_init__(self):\n58:         if \"\\r\" in self.line or \"\\n\" in self.line:\n59:             raise ValueError(\"CLI commands must contain exactly one line\")\n60: \n61:     @property\n62:     def closes_scope(self):\n63:         return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n64: \n65: \n66: @dataclass\n67: class CommandAttempt:\n68:     spec: CommandSpec\n69:     number: int\n70:     session_epoch: int\n71:     output: bytearray = field(default_factory=bytearray)\n72:     prompt_context_before: tuple | None = None\n73:     prompt_context_after: tuple | None = None\n74:     block_index: int | None = None\n75:     retry_count: int = 0\n76: \n77:     def on_output(self, output):\n78:         if not (self.spec.capture_output or self.spec.closes_scope):\n79:             return False\n80:         data = bytes(output)\n81:         self.output.extend(data)\n82:         output.discard(data)\n83:         return True\n84: \n85: \n86: class Scope:\n87:     def __init__(self, value, children=()):\n88:         self.value = value\n89:         self.children = list(children)\n90: \n91:     @property\n92:     def open_line(self):\n93:         raise NotImplementedError\n94: \n95:     @property\n96:     def close_line(self):\n97:         raise NotImplementedError\n98: \n99:     def flatten(self):\n100:         commands = flatten_commands(self.open_line)\n101:         for child in self.children:\n102:             commands.extend(flatten_commands(child))\n103:         commands.append(CommandSpec(self.close_line))\n104:         return commands\n105: \n106: \n107: class ConfigBlock(Scope):\n108:     @property\n109:     def open_line(self):\n110:         return f\"config {self.value}\"\n111: \n112:     @property\n113:     def close_line(self):\n114:         return \"end\"\n115: \n116: \n117: class EditBlock(Scope):\n118:     @property\n119:     def open_line(self):\n120:         return f\"edit {self.value}\"\n121: \n122:     @property\n123:     def close_line(self):\n124:         return \"next\"\n125: \n126: \n127: class SetValue:\n128:     \"\"\"A quoted ``set`` command supporting FortiOS continuation prompts.\"\"\"\n129: \n130:     def __init__(self, field, value, fail_on_error=True, validate_prompt=True):\n131:         self.field = field\n132:         self.value = value\n133:         self.fail_on_error = fail_on_error\n134:         self.validate_prompt = validate_prompt\n135: \n136:     def flatten(self):\n137:         lines = str(self.value).strip().splitlines() or [\"\"]\n138:         lines[0] = f'set {self.field} \"{lines[0]}'\n139:         lines[-1] += '\"'\n140:         return _flatten_quoted_lines(\n141:             lines, fail_on_error=self.fail_on_error,\n142:             validate_prompt=self.validate_prompt,\n143:         )\n144: \n145: \n146: def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n147:     \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n148:     commands = []\n149:     for index, line in enumerate(lines):\n150:         last_line = index == len(lines) - 1\n151:         expected = (\n152:             FOSCliState.CMD_PROMPT if last_line\n153:             else FOSCliState.MULTILINE_PROMPT\n154:         )\n155:         completion_states = ()\n156:         if len(lines) > 1:\n157:             completion_states = (\n158:                 (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n159:                 if last_line else\n160:                 (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n161:             )\n162:         commands.append(CommandSpec(\n163:             line,\n164:             completion_states=completion_states,\n165:             capture_output=True,\n166:             expected_completion_state=expected if validate_prompt else None,\n167:             fail_on_error=fail_on_error,\n168:             continuation=index > 0,\n169:         ))\n170:     return commands\n171: \n172: \n173: class CommandSequence:\n174:     \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n175: \n176:     def __init__(self, name, children=()):\n177:         self.name = name\n178:         self.children = list(children)\n179: \n180:     def flatten(self):\n181:         commands = []\n182:         for child in self.children:\n183:             commands.extend(flatten_commands(child))\n184:         return commands\n185: \n186: \n187: def flatten_commands(value):\n188:     \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n189:     if isinstance(value, str):\n190:         if \"\\n\" in value:\n191:             return _flatten_quoted_lines(value.split(\"\\n\"))\n192:         return [CommandSpec(value)]\n193:     if isinstance(value, CommandSpec):\n194:         return [value]\n195:     if isinstance(value, (Scope, CommandSequence, SetValue)):\n196:         return value.flatten()\n197:     raise TypeError(\n198:         \"Commands must be strings, CommandSpec instances, or command containers\"\n199:     )\n200: \n201: \n202: @dataclass(frozen=True)\n203: class CleanupAction:\n204:     name: str\n205:     block: object\n206:     on_completion: bool = True\n207:     on_interruption: bool = True\n\n(End of file - total 207 lines)\n</content>",
    "title": "source/head/fortinet/common/cli_commands.py",
    "metadata": {
      "preview": "        object.__setattr__(self, \"continuation\", continuation)\n        if context_loss is None:\n            # Commands that must not replay after logout must not replay after\n            # an unexpected scope exit either. Features can override this policy.\n            context_loss = (\n                ContextLossAction.RESTART_BLOCK\n                if session_loss == SessionLossAction.RESTART_BLOCK\n                else ContextLossAction.FAIL\n            )\n        object.__setattr__(self, \"context_loss\", context_loss)\n        self.__post_init__()\n\n    def __post_init__(self):\n        if \"\\r\" in self.line or \"\\n\" in self.line:\n            raise ValueError(\"CLI commands must contain exactly one line\")\n\n    @property\n    def closes_scope(self):\n        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/cli_commands.py",
        "text": "        object.__setattr__(self, \"continuation\", continuation)\n        if context_loss is None:\n            # Commands that must not replay after logout must not replay after\n            # an unexpected scope exit either. Features can override this policy.\n            context_loss = (\n                ContextLossAction.RESTART_BLOCK\n                if session_loss == SessionLossAction.RESTART_BLOCK\n                else ContextLossAction.FAIL\n            )\n        object.__setattr__(self, \"context_loss\", context_loss)\n        self.__post_init__()\n\n    def __post_init__(self):\n        if \"\\r\" in self.line or \"\\n\" in self.line:\n            raise ValueError(\"CLI commands must contain exactly one line\")\n\n    @property\n    def closes_scope(self):\n        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n\n\n@dataclass\nclass CommandAttempt:\n    spec: CommandSpec\n    number: int\n    session_epoch: int\n    output: bytearray = field(default_factory=bytearray)\n    prompt_context_before: tuple | None = None\n    prompt_context_after: tuple | None = None\n    block_index: int | None = None\n    retry_count: int = 0\n\n    def on_output(self, output):\n        if not (self.spec.capture_output or self.spec.closes_scope):\n            return False\n        data = bytes(output)\n        self.output.extend(data)\n        output.discard(data)\n        return True\n\n\nclass Scope:\n    def __init__(self, value, children=()):\n        self.value = value\n        self.children = list(children)\n\n    @property\n    def open_line(self):\n        raise NotImplementedError\n\n    @property\n    def close_line(self):\n        raise NotImplementedError\n\n    def flatten(self):\n        commands = flatten_commands(self.open_line)\n        for child in self.children:\n            commands.extend(flatten_commands(child))\n        commands.append(CommandSpec(self.close_line))\n        return commands\n\n\nclass ConfigBlock(Scope):\n    @property\n    def open_line(self):\n        return f\"config {self.value}\"\n\n    @property\n    def close_line(self):\n        return \"end\"\n\n\nclass EditBlock(Scope):\n    @property\n    def open_line(self):\n        return f\"edit {self.value}\"\n\n    @property\n    def close_line(self):\n        return \"next\"\n\n\nclass SetValue:\n    \"\"\"A quoted ``set`` command supporting FortiOS continuation prompts.\"\"\"\n\n    def __init__(self, field, value, fail_on_error=True, validate_prompt=True):\n        self.field = field\n        self.value = value\n        self.fail_on_error = fail_on_error\n        self.validate_prompt = validate_prompt\n\n    def flatten(self):\n        lines = str(self.value).strip().splitlines() or [\"\"]\n        lines[0] = f'set {self.field} \"{lines[0]}'\n        lines[-1] += '\"'\n        return _flatten_quoted_lines(\n            lines, fail_on_error=self.fail_on_error,\n            validate_prompt=self.validate_prompt,\n        )\n\n\ndef _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n    commands = []\n    for index, line in enumerate(lines):\n        last_line = index == len(lines) - 1\n        expected = (\n            FOSCliState.CMD_PROMPT if last_line\n            else FOSCliState.MULTILINE_PROMPT\n        )\n        completion_states = ()\n        if len(lines) > 1:\n            completion_states = (\n                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n                if last_line else\n                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n            )\n        commands.append(CommandSpec(\n            line,\n            completion_states=completion_states,\n            capture_output=True,\n            expected_completion_state=expected if validate_prompt else None,\n            fail_on_error=fail_on_error,\n            continuation=index > 0,\n        ))\n    return commands\n\n\nclass CommandSequence:\n    \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n\n    def __init__(self, name, children=()):\n        self.name = name\n        self.children = list(children)\n\n    def flatten(self):\n        commands = []\n        for child in self.children:\n            commands.extend(flatten_commands(child))\n        return commands\n\n\ndef flatten_commands(value):\n    \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n    if isinstance(value, str):\n        if \"\\n\" in value:\n            return _flatten_quoted_lines(value.split(\"\\n\"))\n        return [CommandSpec(value)]\n    if isinstance(value, CommandSpec):\n        return [value]\n    if isinstance(value, (Scope, CommandSequence, SetValue)):\n        return value.flatten()\n    raise TypeError(\n        \"Commands must be strings, CommandSpec instances, or command containers\"\n    )\n\n\n@dataclass(frozen=True)\nclass CleanupAction:\n    name: str\n    block: object\n    on_completion: bool = True\n    on_interruption: bool = True",
        "lineStart": 45,
        "lineEnd": 207,
        "totalLines": 207,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716545262,
      "end": 1793716545269
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d666f80013MKX5ziWdTEHd5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d645de0015j2Xa816gxTk2E",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 9148,
    "input": 8120,
    "output": 113,
    "reasoning": 915,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d645de0015j2Xa816gxTk2E",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716536798,
    "completed": 1793716545276
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 9148,
    "input": 8120,
    "output": 113,
    "reasoning": 915,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 25
step-start
{
  "type": "step-start",
  "id": "prt_1a1d66dde001V61uiG7OVUT1ZQ",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6670200104Gc8tYpgFupal"
}
Reasoning
Good. fos_commander.py is only 687 lines total, so I've read lines 1-687? Earlier I read first 700 → actually read up to 687, so the whole file. Good.

Now read the rest: cli_commands.py lines 1-44 (I read first 45 earlier — need lines 1-44), launch.py rest, common.py rest, features/license.py, features/credentials.py, features/pki.py, and the tests + READMEs.
`fos_commander.py` is fully read (687 lines). Now let me get the head of `cli_commands.py`, the rest of `launch.py`, `common.py`, and the remaining feature files.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/cli_commands.py",
  "limit": 45
}

Output

<path>/source/head/fortinet/common/cli_commands.py</path>
<type>file</type>
<content>
1: """Command and scope data used by the FortiOS CLI scheduler."""
2: 
3: from dataclasses import dataclass, field
4: from enum import Enum, auto
5: 
6: from .common import FOSCliState
7: 
8: 
9: class SessionLossAction(Enum):
10:     RESTART_BLOCK = auto()
11:     COMPLETE_BLOCK = auto()
12:     CONTINUE = auto()
13:     VALIDATE = auto()
14:     FAIL = auto()
15: 
16: 
17: class ContextLossAction(Enum):
18:     RESTART_BLOCK = auto()
19:     FAIL = auto()
20: 
21: 
22: @dataclass(frozen=True, init=False)
23: class CommandSpec:
24:     line: str
25:     completion_states: tuple = ()
26:     capture_output: bool = False
27:     suppress_output: bool = False
28:     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK
29:     expected_completion_state: object = None
30:     fail_on_error: bool = False
31:     context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK
32:     continuation: bool = False
33: 
34:     def __init__(self, line, completion_states=(), capture_output=False,
35:                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,
36:                  expected_completion_state=None, fail_on_error=False,
37:                  context_loss=None, continuation=False):
38:         object.__setattr__(self, "line", line)
39:         object.__setattr__(self, "completion_states", completion_states)
40:         object.__setattr__(self, "capture_output", capture_output)
41:         object.__setattr__(self, "suppress_output", suppress_output)
42:         object.__setattr__(self, "session_loss", session_loss)
43:         object.__setattr__(self, "expected_completion_state", expected_completion_state)
44:         object.__setattr__(self, "fail_on_error", fail_on_error)
45:         object.__setattr__(self, "continuation", continuation)

(Showing lines 1-45 of 207. Use offset=46 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d67251001RUJQ6kgdPwr7mx",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6670200104Gc8tYpgFupal",
  "callID": "call_2fac9c6b141144a9a8720d06",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/cli_commands.py",
      "limit": 45
    },
    "output": "<path>/source/head/fortinet/common/cli_commands.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n2: \n3: from dataclasses import dataclass, field\n4: from enum import Enum, auto\n5: \n6: from .common import FOSCliState\n7: \n8: \n9: class SessionLossAction(Enum):\n10:     RESTART_BLOCK = auto()\n11:     COMPLETE_BLOCK = auto()\n12:     CONTINUE = auto()\n13:     VALIDATE = auto()\n14:     FAIL = auto()\n15: \n16: \n17: class ContextLossAction(Enum):\n18:     RESTART_BLOCK = auto()\n19:     FAIL = auto()\n20: \n21: \n22: @dataclass(frozen=True, init=False)\n23: class CommandSpec:\n24:     line: str\n25:     completion_states: tuple = ()\n26:     capture_output: bool = False\n27:     suppress_output: bool = False\n28:     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n29:     expected_completion_state: object = None\n30:     fail_on_error: bool = False\n31:     context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n32:     continuation: bool = False\n33: \n34:     def __init__(self, line, completion_states=(), capture_output=False,\n35:                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n36:                  expected_completion_state=None, fail_on_error=False,\n37:                  context_loss=None, continuation=False):\n38:         object.__setattr__(self, \"line\", line)\n39:         object.__setattr__(self, \"completion_states\", completion_states)\n40:         object.__setattr__(self, \"capture_output\", capture_output)\n41:         object.__setattr__(self, \"suppress_output\", suppress_output)\n42:         object.__setattr__(self, \"session_loss\", session_loss)\n43:         object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n44:         object.__setattr__(self, \"fail_on_error\", fail_on_error)\n45:         object.__setattr__(self, \"continuation\", continuation)\n\n(Showing lines 1-45 of 207. Use offset=46 to continue.)\n</content>",
    "title": "source/head/fortinet/common/cli_commands.py",
    "metadata": {
      "preview": "\"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\n\nfrom .common import FOSCliState\n\n\nclass SessionLossAction(Enum):\n    RESTART_BLOCK = auto()\n    COMPLETE_BLOCK = auto()\n    CONTINUE = auto()\n    VALIDATE = auto()\n    FAIL = auto()\n\n\nclass ContextLossAction(Enum):\n    RESTART_BLOCK = auto()\n    FAIL = auto()\n",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/cli_commands.py",
        "text": "\"\"\"Command and scope data used by the FortiOS CLI scheduler.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\n\nfrom .common import FOSCliState\n\n\nclass SessionLossAction(Enum):\n    RESTART_BLOCK = auto()\n    COMPLETE_BLOCK = auto()\n    CONTINUE = auto()\n    VALIDATE = auto()\n    FAIL = auto()\n\n\nclass ContextLossAction(Enum):\n    RESTART_BLOCK = auto()\n    FAIL = auto()\n\n\n@dataclass(frozen=True, init=False)\nclass CommandSpec:\n    line: str\n    completion_states: tuple = ()\n    capture_output: bool = False\n    suppress_output: bool = False\n    session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n    expected_completion_state: object = None\n    fail_on_error: bool = False\n    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n    continuation: bool = False\n\n    def __init__(self, line, completion_states=(), capture_output=False,\n                 suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n                 expected_completion_state=None, fail_on_error=False,\n                 context_loss=None, continuation=False):\n        object.__setattr__(self, \"line\", line)\n        object.__setattr__(self, \"completion_states\", completion_states)\n        object.__setattr__(self, \"capture_output\", capture_output)\n        object.__setattr__(self, \"suppress_output\", suppress_output)\n        object.__setattr__(self, \"session_loss\", session_loss)\n        object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n        object.__setattr__(self, \"fail_on_error\", fail_on_error)\n        object.__setattr__(self, \"continuation\", continuation)",
        "lineStart": 1,
        "lineEnd": 45,
        "totalLines": 207,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716548180,
      "end": 1793716548185
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/launch.py",
  "offset": 61
}

Output

<path>/source/head/fortinet/common/launch.py</path>
<type>file</type>
<content>
61: logging.addLevelName(TRACE_LEVEL_NUM, "\x1b[1;35m\tTRACE\x1b[0m")
62: LOG_LEVEL_NAMES = {
63:     "TRACE": TRACE_LEVEL_NUM,
64:     "DEBUG": logging.DEBUG,
65:     "INFO": logging.INFO,
66:     "WARN": logging.WARN,
67:     "WARNING": logging.WARNING,
68:     "ERROR": logging.ERROR,
69:     "CRITICAL": logging.CRITICAL,
70:     "FATAL": logging.FATAL,
71: }
72: 
73: 
74: def trace(self, message, *args, **kws):
75:     # Yes, logger takes its '*args' as 'args'.
76:     if self.isEnabledFor(TRACE_LEVEL_NUM):
77:         self.log(TRACE_LEVEL_NUM, message, *args, **kws)
78: 
79: 
80: logging.Logger.trace = trace
81: MGMT_PASSTHROUGH_DEFAULT = True
82: TFTP_PORT = 69
83: TFTP_TID_RANGE = (52400, 52500)
84: TFTP_DIRECTORY = "/tftpboot"
85: 
86: 
87: def parse_log_level(value):
88:     if value is None or str(value).strip() == "":
89:         return logging.DEBUG
90:     value = str(value).strip()
91:     try:
92:         return int(value)
93:     except ValueError:
94:         pass
95:     normalized = value.upper()
96:     if normalized in LOG_LEVEL_NAMES:
97:         return LOG_LEVEL_NAMES[normalized]
98:     raise ValueError(
99:         "Invalid FOS_LOG_LEVEL. Use TRACE, DEBUG, INFO, WARN, ERROR, "
100:         "another Python logging level name, or a numeric level."
101:     )
102: 
103: 
104: def exit_on_bootstrap_error(value=None):
105:     """Return whether a bootstrap exception should terminate the VM.
106: 
107:     Bootstrap failures are fatal by default.  The opt-out is intentionally
108:     narrow: only the explicit value ``false`` disables termination, so a
109:     misspelled or otherwise invalid value keeps the fail-fast behavior.
110:     """
111:     if value is None:
112:         value = get_env("FOS_EXIT_ON_BOOTSTRAP_ERROR", "true")
113:     return str(value).strip().lower() != "false"
114: 
115: 
116: def container_dns_servers(path="/etc/resolv.conf"):
117:     """Return nameserver addresses configured for this container, in order."""
118:     try:
119:         with open(path, encoding="utf-8") as resolver_config:
120:             servers = []
121:             for line in resolver_config:
122:                 fields = line.split()
123:                 if len(fields) >= 2 and fields[0] == "nameserver":
124:                     servers.append(fields[1])
125:             return servers
126:     except OSError:
127:         return []
128: 
129: 
130: def apply_debug_feature_cutoff(features, stop_feature, logger):
131:     """Limit bootstrap features to those up to and including ``stop_feature``."""
132:     if stop_feature is None or str(stop_feature).strip() == "":
133:         return features
134: 
135:     stop_feature = str(stop_feature).strip()
136:     for index, feature in enumerate(features):
137:         if feature.name == stop_feature:
138:             selected = features[:index + 1]
139:             skipped = features[index + 1:]
140:             logger.warning(
141:                 "FOS_DEBUG_FEATURE=%s; stopping after feature %s. Skipping: %s",
142:                 stop_feature,
143:                 stop_feature,
144:                 ", ".join(feature.name for feature in skipped) or "(none)",
145:             )
146:             return selected
147: 
148:     available = ", ".join(feature.name for feature in features)
149:     raise ValueError(f"Unknown FOS_DEBUG_FEATURE '{stop_feature}'. Available features: {available}")
150: 
151: 
152: class FortiOSConsole(vrnetlab._Console):
153:     def __init__(self, driver):
154:         super().__init__(driver)
155:         self._output_enabled = True
156: 
157:     def _read(self):
158:         data = self._driver.channel.read()
159:         if data and self._output_enabled:
160:             sys.stdout.buffer.write(data)
161:             sys.stdout.buffer.flush()
162:         return data
163: 
164:     def read_very_eager(self):
165:         transport_socket = getattr(self._driver.transport, "socket", None)
166:         socket = getattr(transport_socket, "sock", None)
167:         if socket is not None:
168:             readable, _, _ = select.select([socket], [], [], 0)
169:             if not readable:
170:                 return b""
171:         return self._read()
172: 
173:     def read_blocking(self):
174:         return self._read()
175: 
176:     @contextmanager
177:     def suppress_output(self):
178:         output_enabled = self._output_enabled
179:         self._output_enabled = False
180:         try:
181:             yield
182:         finally:
183:             self._output_enabled = output_enabled
184: 
185: 
186: class FortiOS_vm(vrnetlab.VM):
187:     def __init__(self, hostname: str, username, password, conn_mode, mgmt_net: NetMgmtStrategy,
188:                  expected_product="FortiGate"):
189:         disk_image = None
190:         for e in os.listdir("."):
191:             if re.search(".qcow2$", e):
192:                 disk_image = "./" + e
193:         if disk_image is None:
194:             raise RuntimeError("Could not find image to boot")
195:         super(FortiOS_vm, self).__init__(
196:             username,
197:             password,
198:             disk_image=disk_image,
199:             ram=2048,
200:             driveif="virtio",
201:             # fortios fails to respond to network requests if the pci bus is setup :D
202:             provision_pci_bus=False,
203:             mgmt_passthrough=mgmt_net.mgmt_passthrough
204:         )
205:         self.tn = FortiOSConsole(self.scrapli_tn)
206: 
207:         self.logger.info(f"Launching. commandline: {' '.join(sys.argv)}")
208:         self.logger.warning("deploy --reconfigure, deploy --restore, redeploy, restart, restore, save, stop-then-start,"
209:                             " not supported at this moment.")
210:         self.conn_mode = conn_mode
211:         self.hostname = hostname
212:         self.num_nics = 12
213:         self.nic_type = "virtio-net-pci"
214:         self.highest_port = 0
215:         self.spins = 0
216:         self.stopped = False
217:         self._bootstrap_error = None
218:         self._exit_on_bootstrap_error = exit_on_bootstrap_error()
219:         self.waiting_for = False
220:         self._mgmt_net = mgmt_net
221:         self.expected_product = expected_product
222:         self._mgmt_net.configure_vm_mgmt(self)
223:         container_dns = container_dns_servers()
224:         primary_dns = get_env(
225:             "FOS_MGMT_DNS_PRIMARY",
226:             aliases=("FTNT_DNS_PRIMARY",),
227:         )
228:         secondary_dns = get_env(
229:             "FOS_MGMT_DNS_SECONDARY",
230:             aliases=("FTNT_DNS_SECONDARY",),
231:             legacy_aliases=("FTNT_MGMG_DNS_SECONDARY", "FOS_MGMG_DNS_SECONDARY"),
232:         )
233:         if primary_dns is None:
234:             primary_dns = container_dns[0] if container_dns else "1.1.1.1"
235:         if secondary_dns is None:
236:             secondary_dns = container_dns[1] if len(container_dns) > 1 else "8.8.8.8"
237:         self.mgmt_dns_primary = primary_dns
238:         self.mgmt_dns_secondary = secondary_dns
239:         self.mgmt_dns_protocol = get_env("FTNT_DNS_PROTOCOL", "cleartext")
240:         self.terminal = Terminal(self.tn, self.logger, default_wait=self.wait_pattern)
241:         desired_password = DEFAULT_PASSWORD if password is None else password
242:         self._bootstrap_username = DEFAULT_USERNAME
243:         self._bootstrap_password = DEF_POLICY_COMPLIANT_PASSWORD
244:         self.credentials = Credentials(self._bootstrap_username, self._bootstrap_password)
245:         self.desired_credentials = Credentials(username or DEFAULT_USERNAME, desired_password)
246:         self.commander = FOSCommander(
247:             terminal=self.terminal,
248:             logger=self.logger,
249:             continue_on_error=not self._exit_on_bootstrap_error,
250:         )
251:         self.fos_version = None
252:         self.fos_product = None
253:         self.driver = FOSCliDriver(
254:             self.terminal,
255:             self.commander,
256:             self.credentials,
257:             self.logger,
258:             self._bootstrap_password,
259:             self.activate_blank_credentials,
260:             self.activate_bootstrap_credentials,
261:             # Always retry the last accepted credentials after a desired
262:             # password transition is rejected. The bootstrap error policy
263:             # controls feature failures, not whether the console can recover.
264:             allow_credential_recovery=True,
265:         )
266:         configure_dns = ConfigureMgmtDns(self, self.commander)
267:         license_validation = WaitForLicenseValidation(self, self.commander)
268:         self._features = [
269:             ImageInfo(self, self.commander),
270:             ValidateProduct(self, self.commander, expected_product),
271:             FormatDisks(self, self.commander),
272:             CredentialsFeature(self, self.commander),
273:             ConfigureMgmtNetwork(self, self.commander),
274:             configure_dns,
275:             ConfigureFortiGuardHooks(self, self.commander),
276:             SetLicense(self, self.commander),
277:             ReapplyFortiGuardHooks(self, self.commander),
278:             DefaultConfig(self, self.commander),
279:             ReconfigureMgmtNetwork(self, self.commander),
280:             license_validation,
281:             WaitForFortiTokens(self, self.commander, license_validation),
282:             InstallPkiCertificates(self, self.commander),
283:             MoveMgmtToVrf1(self, self.commander),
284:             ConfigSaveFeature(self, self.commander),
285:             ApplyStartupConfig(self, self.commander),
286:         ]
287:         self._features = apply_debug_feature_cutoff(
288:             self._features,
289:             get_env("FOS_DEBUG_FEATURE"),
290:             self.logger,
291:         )
292:         self._file_watcher = FeatureFileWatcher(self._features, self.logger)
293:         self.commander.start(self._features)
294:         vrnetlab.run_command(
295:             ["qemu-img", "create", "-f", "qcow2", "empty.qcow2", "30G"]
296:         )
297: 
298:         # Comma-separated list of disk sizes to install in the machine. as accepted by qemu-img create.
299:         disk_specs = get_env("FOS_DISK_SPECS", "").split(",")
300:         if disk_specs[0] == '':
301:             self.logger.warning(
302:                 "No additional disks configured. Use FOS_DISK_SPECS to specify a comma-separated list of disk sizes")
303:             return
304:         index = 0
305:         for spec in disk_specs:
306:             index += 1
307:             # set up the extra empty disk image
308:             # for fortigate logs
309:             vrnetlab.run_command(
310:                 ["qemu-img", "create", "-f", "qcow2", f"empty{index}.qcow2", spec]
311:             )
312: 
313:             self.qemu_args.extend(
314:                 [
315:                     "-drive",
316:                     f"if=virtio,format=qcow2,file=empty{index}.qcow2,index={index}",
317:                 ]
318:             )
319: 
320:             index += 1
321: 
322:     def bootstrap_spin(self):
323:         """This function should be called periodically to do work.
324: 
325:         returns False when it has failed and given up, otherwise True
326:         """
327:         if self._bootstrap_error is not None:
328:             return False
329:         try:
330:             self.driver.process_state()
331:         except KernelPanicError:
332:             self.stop()
333:             raise
334:         except Exception as error:
335:             if self._exit_on_bootstrap_error or self.commander.startup_complete:
336:                 self.stop()
337:                 raise
338:             failed_work = self.commander.continue_after_error(
339:                 error,
340:                 at_command_prompt=self.driver.at_command_prompt,
341:             )
342:             if failed_work is not None:
343:                 self.logger.exception(
344:                     "Bootstrap work %s failed; continuing with remaining features "
345:                     "because FOS_EXIT_ON_BOOTSTRAP_ERROR=false",
346:                     failed_work,
347:                 )
348:                 return True
349:             self._bootstrap_error = error
350:             self.logger.exception(
351:                 "Bootstrap cannot continue safely; keeping the VM running for manual "
352:                 "repair because FOS_EXIT_ON_BOOTSTRAP_ERROR=false"
353:             )
354:             try:
355:                 self.terminal.close()
356:                 self.logger.info(
357:                     "Released the launcher's serial Telnet connection after bootstrap stopped"
358:                 )
359:             except Exception:
360:                 self.logger.exception(
361:                     "Failed to release the serial Telnet connection after bootstrap stopped"
362:                 )
363:             return False
364:         if self.driver.ready and not self.commander.feature_errors:
365:             self.running = True
366:         return True
367: 
368:     def work(self):
369:         self._write_heartbeat()
370:         super().work()
371:         if self.running:
372:             self._file_watcher.poll()
373:             if not self.driver.ready:
374:                 self.bootstrap_spin()
375: 
376:     def _write_heartbeat(self):
377:         """Append one byte to the healthcheck heartbeat file.
378: 
379:         ``fos_healthcheck.py`` blocks in "starting" as long as this file
380:         keeps growing, so a slow but progressing bootstrap never trips the
381:         Docker unhealthy threshold. A wedged launcher stops beating and the
382:         probe reports failure. Best-effort: a heartbeat write must never
383:         take down the main loop.
384:         """
385:         try:
386:             with open(HEARTBEAT_FILE, "a") as heartbeat_handle:
387:                 heartbeat_handle.write("\n")
388:         except OSError:
389:             self.logger.debug("Failed to write healthcheck heartbeat", exc_info=True)
390: 
391:     def connect_serial_console(self):
392:         try:
393:             self.terminal.close()
394:         except Exception:
395:             pass
396: 
397:         for attempt in range(1, vrnetlab.MAX_RETRIES + 1):
398:             try:
399:                 self.tn.open()
400:                 break
401:             except Exception:
402:                 if attempt == vrnetlab.MAX_RETRIES:
403:                     self.logger.exception("Failed to connect to VM serial port.")
404:                     self.stop()
405:                     raise
406:                 self.logger.error(
407:                     f"Unable to connect to VM serial port {5000 + self.num}, "
408:                     f"retrying in a second (attempt {attempt})"
409:                 )
410:                 time.sleep(1)
411: 
412:         self.stopped = False
413:         self.terminal.write(b"\r")
414: 
415:     def activate_desired_credentials(self):
416:         self.driver.remember_current_credentials()
417:         self.credentials.username = self.desired_credentials.username
418:         self.credentials.password = self.desired_credentials.password
419: 
420:     def activate_bootstrap_credentials(self):
421:         self.credentials.username = self._bootstrap_username
422:         self.credentials.password = self._bootstrap_password
423: 
424:     def activate_blank_credentials(self):
425:         self.credentials.password = ""
426: 
427:     def gen_mgmt(self):
428:         return self._mgmt_net.gen_mgmt(self)
429: 
430:     @staticmethod
431:     def mgmt_gateway_destination(gateway, mgmt_address):
432:         _address, separator, prefix = str(mgmt_address).partition("/")
433:         if separator and prefix:
434:             return f"{gateway}/{prefix}"
435:         return f"{gateway}/{'128' if ':' in str(gateway) else '32'}"
436: 
437:     def stop(self):
438:         self.stopped = True
439:         super().stop()
440: 
441: 
442: class FortiOS(vrnetlab.VR):
443:     def __init__(self, hostname, username, password, conn_mode, mgmt_net: NetMgmtStrategy,
444:                  expected_product="FortiGate"):
445:         super(FortiOS, self).__init__(username, password, mgmt_passthrough=mgmt_net.mgmt_passthrough)
446:         self.logger.debug("Hostname")
447:         self.logger.debug(hostname)
448:         self.vms = [FortiOS_vm(hostname, username, password, conn_mode, mgmt_net=mgmt_net,
449:                                expected_product=expected_product)]
450: 
451: 
452: def main(expected_product="FortiGate"):
453: 
454:     parser = argparse.ArgumentParser(description="")
455:     parser.add_argument(
456:         "--trace", action="store_true", help="enable trace level logging"
457:     )
458:     parser.add_argument("--hostname", default="vr-fortinet", help="Fortinet hostname")
459:     parser.add_argument("--username", default=None, help="Username")
460:     parser.add_argument("--password", default=None, help="Password", nargs="?")
461:     parser.add_argument(
462:         "--connection-mode",
463:         default="tc",
464:         help="Connection mode to use in the datapath",
465:     )
466:     args = parser.parse_args()
467: 
468:     LOG_FORMAT = "%(asctime)s: %(module)-10s %(levelname)-8s %(message)s"
469:     logging.basicConfig(format=LOG_FORMAT)
470:     logger = logging.getLogger()
471: 
472:     logger.setLevel(parse_log_level(get_env("FOS_LOG_LEVEL")))
473: 
474:     mgmt_passthrough = (
475:         os.environ.get("CLAB_MGMT_PASSTHROUGH", "").lower() == "true"
476:         if os.environ.get("CLAB_MGMT_PASSTHROUGH")
477:         else MGMT_PASSTHROUGH_DEFAULT
478:     )
479: 
480:     tftp_server = None
481:     mgmt_net = None
482:     if mgmt_passthrough:
483:         mgmt_net = PassthroughRedirect([f"udp:{TFTP_PORT}", f"udp:{'-'.join(map(str, TFTP_TID_RANGE))}"])
484:         mgmt_net.prep()
485:         tftp_server = TFTPServer(mgmt_net=mgmt_net,
486:                                  srv_port=TFTP_PORT,
487:                                  tid_range=TFTP_TID_RANGE,
488:                                  directory=TFTP_DIRECTORY)
489:     else:
490:         mgmt_net = HostForwardedBridge()
491:         mgmt_net.prep()
492:         tftp_server = TFTPServer(srv_port=TFTP_PORT,
493:                                  mgmt_net=mgmt_net,
494:                                  directory=TFTP_DIRECTORY)
495: 
496:     vr = FortiOS(
497:         args.hostname, args.username, args.password, conn_mode=args.connection_mode,
498:         mgmt_net=mgmt_net, expected_product=expected_product
499:     )
500:     tftp_server.launch()
501:     vrnetlab.boot_delay()
502:     vr.start()
503: 
504: 
505: if __name__ == "__main__":
506:     main(get_env("FOS_EXPECTED_PRODUCT", "FortiGate"))

(End of file - total 506 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d67293001B1rEKT8F0cJ53P",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6670200104Gc8tYpgFupal",
  "callID": "call_def41dd9da5b4dadb5fbbad8",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/launch.py",
      "offset": 61
    },
    "output": "<path>/source/head/fortinet/common/launch.py</path>\n<type>file</type>\n<content>\n61: logging.addLevelName(TRACE_LEVEL_NUM, \"\\x1b[1;35m\\tTRACE\\x1b[0m\")\n62: LOG_LEVEL_NAMES = {\n63:     \"TRACE\": TRACE_LEVEL_NUM,\n64:     \"DEBUG\": logging.DEBUG,\n65:     \"INFO\": logging.INFO,\n66:     \"WARN\": logging.WARN,\n67:     \"WARNING\": logging.WARNING,\n68:     \"ERROR\": logging.ERROR,\n69:     \"CRITICAL\": logging.CRITICAL,\n70:     \"FATAL\": logging.FATAL,\n71: }\n72: \n73: \n74: def trace(self, message, *args, **kws):\n75:     # Yes, logger takes its '*args' as 'args'.\n76:     if self.isEnabledFor(TRACE_LEVEL_NUM):\n77:         self.log(TRACE_LEVEL_NUM, message, *args, **kws)\n78: \n79: \n80: logging.Logger.trace = trace\n81: MGMT_PASSTHROUGH_DEFAULT = True\n82: TFTP_PORT = 69\n83: TFTP_TID_RANGE = (52400, 52500)\n84: TFTP_DIRECTORY = \"/tftpboot\"\n85: \n86: \n87: def parse_log_level(value):\n88:     if value is None or str(value).strip() == \"\":\n89:         return logging.DEBUG\n90:     value = str(value).strip()\n91:     try:\n92:         return int(value)\n93:     except ValueError:\n94:         pass\n95:     normalized = value.upper()\n96:     if normalized in LOG_LEVEL_NAMES:\n97:         return LOG_LEVEL_NAMES[normalized]\n98:     raise ValueError(\n99:         \"Invalid FOS_LOG_LEVEL. Use TRACE, DEBUG, INFO, WARN, ERROR, \"\n100:         \"another Python logging level name, or a numeric level.\"\n101:     )\n102: \n103: \n104: def exit_on_bootstrap_error(value=None):\n105:     \"\"\"Return whether a bootstrap exception should terminate the VM.\n106: \n107:     Bootstrap failures are fatal by default.  The opt-out is intentionally\n108:     narrow: only the explicit value ``false`` disables termination, so a\n109:     misspelled or otherwise invalid value keeps the fail-fast behavior.\n110:     \"\"\"\n111:     if value is None:\n112:         value = get_env(\"FOS_EXIT_ON_BOOTSTRAP_ERROR\", \"true\")\n113:     return str(value).strip().lower() != \"false\"\n114: \n115: \n116: def container_dns_servers(path=\"/etc/resolv.conf\"):\n117:     \"\"\"Return nameserver addresses configured for this container, in order.\"\"\"\n118:     try:\n119:         with open(path, encoding=\"utf-8\") as resolver_config:\n120:             servers = []\n121:             for line in resolver_config:\n122:                 fields = line.split()\n123:                 if len(fields) >= 2 and fields[0] == \"nameserver\":\n124:                     servers.append(fields[1])\n125:             return servers\n126:     except OSError:\n127:         return []\n128: \n129: \n130: def apply_debug_feature_cutoff(features, stop_feature, logger):\n131:     \"\"\"Limit bootstrap features to those up to and including ``stop_feature``.\"\"\"\n132:     if stop_feature is None or str(stop_feature).strip() == \"\":\n133:         return features\n134: \n135:     stop_feature = str(stop_feature).strip()\n136:     for index, feature in enumerate(features):\n137:         if feature.name == stop_feature:\n138:             selected = features[:index + 1]\n139:             skipped = features[index + 1:]\n140:             logger.warning(\n141:                 \"FOS_DEBUG_FEATURE=%s; stopping after feature %s. Skipping: %s\",\n142:                 stop_feature,\n143:                 stop_feature,\n144:                 \", \".join(feature.name for feature in skipped) or \"(none)\",\n145:             )\n146:             return selected\n147: \n148:     available = \", \".join(feature.name for feature in features)\n149:     raise ValueError(f\"Unknown FOS_DEBUG_FEATURE '{stop_feature}'. Available features: {available}\")\n150: \n151: \n152: class FortiOSConsole(vrnetlab._Console):\n153:     def __init__(self, driver):\n154:         super().__init__(driver)\n155:         self._output_enabled = True\n156: \n157:     def _read(self):\n158:         data = self._driver.channel.read()\n159:         if data and self._output_enabled:\n160:             sys.stdout.buffer.write(data)\n161:             sys.stdout.buffer.flush()\n162:         return data\n163: \n164:     def read_very_eager(self):\n165:         transport_socket = getattr(self._driver.transport, \"socket\", None)\n166:         socket = getattr(transport_socket, \"sock\", None)\n167:         if socket is not None:\n168:             readable, _, _ = select.select([socket], [], [], 0)\n169:             if not readable:\n170:                 return b\"\"\n171:         return self._read()\n172: \n173:     def read_blocking(self):\n174:         return self._read()\n175: \n176:     @contextmanager\n177:     def suppress_output(self):\n178:         output_enabled = self._output_enabled\n179:         self._output_enabled = False\n180:         try:\n181:             yield\n182:         finally:\n183:             self._output_enabled = output_enabled\n184: \n185: \n186: class FortiOS_vm(vrnetlab.VM):\n187:     def __init__(self, hostname: str, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n188:                  expected_product=\"FortiGate\"):\n189:         disk_image = None\n190:         for e in os.listdir(\".\"):\n191:             if re.search(\".qcow2$\", e):\n192:                 disk_image = \"./\" + e\n193:         if disk_image is None:\n194:             raise RuntimeError(\"Could not find image to boot\")\n195:         super(FortiOS_vm, self).__init__(\n196:             username,\n197:             password,\n198:             disk_image=disk_image,\n199:             ram=2048,\n200:             driveif=\"virtio\",\n201:             # fortios fails to respond to network requests if the pci bus is setup :D\n202:             provision_pci_bus=False,\n203:             mgmt_passthrough=mgmt_net.mgmt_passthrough\n204:         )\n205:         self.tn = FortiOSConsole(self.scrapli_tn)\n206: \n207:         self.logger.info(f\"Launching. commandline: {' '.join(sys.argv)}\")\n208:         self.logger.warning(\"deploy --reconfigure, deploy --restore, redeploy, restart, restore, save, stop-then-start,\"\n209:                             \" not supported at this moment.\")\n210:         self.conn_mode = conn_mode\n211:         self.hostname = hostname\n212:         self.num_nics = 12\n213:         self.nic_type = \"virtio-net-pci\"\n214:         self.highest_port = 0\n215:         self.spins = 0\n216:         self.stopped = False\n217:         self._bootstrap_error = None\n218:         self._exit_on_bootstrap_error = exit_on_bootstrap_error()\n219:         self.waiting_for = False\n220:         self._mgmt_net = mgmt_net\n221:         self.expected_product = expected_product\n222:         self._mgmt_net.configure_vm_mgmt(self)\n223:         container_dns = container_dns_servers()\n224:         primary_dns = get_env(\n225:             \"FOS_MGMT_DNS_PRIMARY\",\n226:             aliases=(\"FTNT_DNS_PRIMARY\",),\n227:         )\n228:         secondary_dns = get_env(\n229:             \"FOS_MGMT_DNS_SECONDARY\",\n230:             aliases=(\"FTNT_DNS_SECONDARY\",),\n231:             legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n232:         )\n233:         if primary_dns is None:\n234:             primary_dns = container_dns[0] if container_dns else \"1.1.1.1\"\n235:         if secondary_dns is None:\n236:             secondary_dns = container_dns[1] if len(container_dns) > 1 else \"8.8.8.8\"\n237:         self.mgmt_dns_primary = primary_dns\n238:         self.mgmt_dns_secondary = secondary_dns\n239:         self.mgmt_dns_protocol = get_env(\"FTNT_DNS_PROTOCOL\", \"cleartext\")\n240:         self.terminal = Terminal(self.tn, self.logger, default_wait=self.wait_pattern)\n241:         desired_password = DEFAULT_PASSWORD if password is None else password\n242:         self._bootstrap_username = DEFAULT_USERNAME\n243:         self._bootstrap_password = DEF_POLICY_COMPLIANT_PASSWORD\n244:         self.credentials = Credentials(self._bootstrap_username, self._bootstrap_password)\n245:         self.desired_credentials = Credentials(username or DEFAULT_USERNAME, desired_password)\n246:         self.commander = FOSCommander(\n247:             terminal=self.terminal,\n248:             logger=self.logger,\n249:             continue_on_error=not self._exit_on_bootstrap_error,\n250:         )\n251:         self.fos_version = None\n252:         self.fos_product = None\n253:         self.driver = FOSCliDriver(\n254:             self.terminal,\n255:             self.commander,\n256:             self.credentials,\n257:             self.logger,\n258:             self._bootstrap_password,\n259:             self.activate_blank_credentials,\n260:             self.activate_bootstrap_credentials,\n261:             # Always retry the last accepted credentials after a desired\n262:             # password transition is rejected. The bootstrap error policy\n263:             # controls feature failures, not whether the console can recover.\n264:             allow_credential_recovery=True,\n265:         )\n266:         configure_dns = ConfigureMgmtDns(self, self.commander)\n267:         license_validation = WaitForLicenseValidation(self, self.commander)\n268:         self._features = [\n269:             ImageInfo(self, self.commander),\n270:             ValidateProduct(self, self.commander, expected_product),\n271:             FormatDisks(self, self.commander),\n272:             CredentialsFeature(self, self.commander),\n273:             ConfigureMgmtNetwork(self, self.commander),\n274:             configure_dns,\n275:             ConfigureFortiGuardHooks(self, self.commander),\n276:             SetLicense(self, self.commander),\n277:             ReapplyFortiGuardHooks(self, self.commander),\n278:             DefaultConfig(self, self.commander),\n279:             ReconfigureMgmtNetwork(self, self.commander),\n280:             license_validation,\n281:             WaitForFortiTokens(self, self.commander, license_validation),\n282:             InstallPkiCertificates(self, self.commander),\n283:             MoveMgmtToVrf1(self, self.commander),\n284:             ConfigSaveFeature(self, self.commander),\n285:             ApplyStartupConfig(self, self.commander),\n286:         ]\n287:         self._features = apply_debug_feature_cutoff(\n288:             self._features,\n289:             get_env(\"FOS_DEBUG_FEATURE\"),\n290:             self.logger,\n291:         )\n292:         self._file_watcher = FeatureFileWatcher(self._features, self.logger)\n293:         self.commander.start(self._features)\n294:         vrnetlab.run_command(\n295:             [\"qemu-img\", \"create\", \"-f\", \"qcow2\", \"empty.qcow2\", \"30G\"]\n296:         )\n297: \n298:         # Comma-separated list of disk sizes to install in the machine. as accepted by qemu-img create.\n299:         disk_specs = get_env(\"FOS_DISK_SPECS\", \"\").split(\",\")\n300:         if disk_specs[0] == '':\n301:             self.logger.warning(\n302:                 \"No additional disks configured. Use FOS_DISK_SPECS to specify a comma-separated list of disk sizes\")\n303:             return\n304:         index = 0\n305:         for spec in disk_specs:\n306:             index += 1\n307:             # set up the extra empty disk image\n308:             # for fortigate logs\n309:             vrnetlab.run_command(\n310:                 [\"qemu-img\", \"create\", \"-f\", \"qcow2\", f\"empty{index}.qcow2\", spec]\n311:             )\n312: \n313:             self.qemu_args.extend(\n314:                 [\n315:                     \"-drive\",\n316:                     f\"if=virtio,format=qcow2,file=empty{index}.qcow2,index={index}\",\n317:                 ]\n318:             )\n319: \n320:             index += 1\n321: \n322:     def bootstrap_spin(self):\n323:         \"\"\"This function should be called periodically to do work.\n324: \n325:         returns False when it has failed and given up, otherwise True\n326:         \"\"\"\n327:         if self._bootstrap_error is not None:\n328:             return False\n329:         try:\n330:             self.driver.process_state()\n331:         except KernelPanicError:\n332:             self.stop()\n333:             raise\n334:         except Exception as error:\n335:             if self._exit_on_bootstrap_error or self.commander.startup_complete:\n336:                 self.stop()\n337:                 raise\n338:             failed_work = self.commander.continue_after_error(\n339:                 error,\n340:                 at_command_prompt=self.driver.at_command_prompt,\n341:             )\n342:             if failed_work is not None:\n343:                 self.logger.exception(\n344:                     \"Bootstrap work %s failed; continuing with remaining features \"\n345:                     \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n346:                     failed_work,\n347:                 )\n348:                 return True\n349:             self._bootstrap_error = error\n350:             self.logger.exception(\n351:                 \"Bootstrap cannot continue safely; keeping the VM running for manual \"\n352:                 \"repair because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\"\n353:             )\n354:             try:\n355:                 self.terminal.close()\n356:                 self.logger.info(\n357:                     \"Released the launcher's serial Telnet connection after bootstrap stopped\"\n358:                 )\n359:             except Exception:\n360:                 self.logger.exception(\n361:                     \"Failed to release the serial Telnet connection after bootstrap stopped\"\n362:                 )\n363:             return False\n364:         if self.driver.ready and not self.commander.feature_errors:\n365:             self.running = True\n366:         return True\n367: \n368:     def work(self):\n369:         self._write_heartbeat()\n370:         super().work()\n371:         if self.running:\n372:             self._file_watcher.poll()\n373:             if not self.driver.ready:\n374:                 self.bootstrap_spin()\n375: \n376:     def _write_heartbeat(self):\n377:         \"\"\"Append one byte to the healthcheck heartbeat file.\n378: \n379:         ``fos_healthcheck.py`` blocks in \"starting\" as long as this file\n380:         keeps growing, so a slow but progressing bootstrap never trips the\n381:         Docker unhealthy threshold. A wedged launcher stops beating and the\n382:         probe reports failure. Best-effort: a heartbeat write must never\n383:         take down the main loop.\n384:         \"\"\"\n385:         try:\n386:             with open(HEARTBEAT_FILE, \"a\") as heartbeat_handle:\n387:                 heartbeat_handle.write(\"\\n\")\n388:         except OSError:\n389:             self.logger.debug(\"Failed to write healthcheck heartbeat\", exc_info=True)\n390: \n391:     def connect_serial_console(self):\n392:         try:\n393:             self.terminal.close()\n394:         except Exception:\n395:             pass\n396: \n397:         for attempt in range(1, vrnetlab.MAX_RETRIES + 1):\n398:             try:\n399:                 self.tn.open()\n400:                 break\n401:             except Exception:\n402:                 if attempt == vrnetlab.MAX_RETRIES:\n403:                     self.logger.exception(\"Failed to connect to VM serial port.\")\n404:                     self.stop()\n405:                     raise\n406:                 self.logger.error(\n407:                     f\"Unable to connect to VM serial port {5000 + self.num}, \"\n408:                     f\"retrying in a second (attempt {attempt})\"\n409:                 )\n410:                 time.sleep(1)\n411: \n412:         self.stopped = False\n413:         self.terminal.write(b\"\\r\")\n414: \n415:     def activate_desired_credentials(self):\n416:         self.driver.remember_current_credentials()\n417:         self.credentials.username = self.desired_credentials.username\n418:         self.credentials.password = self.desired_credentials.password\n419: \n420:     def activate_bootstrap_credentials(self):\n421:         self.credentials.username = self._bootstrap_username\n422:         self.credentials.password = self._bootstrap_password\n423: \n424:     def activate_blank_credentials(self):\n425:         self.credentials.password = \"\"\n426: \n427:     def gen_mgmt(self):\n428:         return self._mgmt_net.gen_mgmt(self)\n429: \n430:     @staticmethod\n431:     def mgmt_gateway_destination(gateway, mgmt_address):\n432:         _address, separator, prefix = str(mgmt_address).partition(\"/\")\n433:         if separator and prefix:\n434:             return f\"{gateway}/{prefix}\"\n435:         return f\"{gateway}/{'128' if ':' in str(gateway) else '32'}\"\n436: \n437:     def stop(self):\n438:         self.stopped = True\n439:         super().stop()\n440: \n441: \n442: class FortiOS(vrnetlab.VR):\n443:     def __init__(self, hostname, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n444:                  expected_product=\"FortiGate\"):\n445:         super(FortiOS, self).__init__(username, password, mgmt_passthrough=mgmt_net.mgmt_passthrough)\n446:         self.logger.debug(\"Hostname\")\n447:         self.logger.debug(hostname)\n448:         self.vms = [FortiOS_vm(hostname, username, password, conn_mode, mgmt_net=mgmt_net,\n449:                                expected_product=expected_product)]\n450: \n451: \n452: def main(expected_product=\"FortiGate\"):\n453: \n454:     parser = argparse.ArgumentParser(description=\"\")\n455:     parser.add_argument(\n456:         \"--trace\", action=\"store_true\", help=\"enable trace level logging\"\n457:     )\n458:     parser.add_argument(\"--hostname\", default=\"vr-fortinet\", help=\"Fortinet hostname\")\n459:     parser.add_argument(\"--username\", default=None, help=\"Username\")\n460:     parser.add_argument(\"--password\", default=None, help=\"Password\", nargs=\"?\")\n461:     parser.add_argument(\n462:         \"--connection-mode\",\n463:         default=\"tc\",\n464:         help=\"Connection mode to use in the datapath\",\n465:     )\n466:     args = parser.parse_args()\n467: \n468:     LOG_FORMAT = \"%(asctime)s: %(module)-10s %(levelname)-8s %(message)s\"\n469:     logging.basicConfig(format=LOG_FORMAT)\n470:     logger = logging.getLogger()\n471: \n472:     logger.setLevel(parse_log_level(get_env(\"FOS_LOG_LEVEL\")))\n473: \n474:     mgmt_passthrough = (\n475:         os.environ.get(\"CLAB_MGMT_PASSTHROUGH\", \"\").lower() == \"true\"\n476:         if os.environ.get(\"CLAB_MGMT_PASSTHROUGH\")\n477:         else MGMT_PASSTHROUGH_DEFAULT\n478:     )\n479: \n480:     tftp_server = None\n481:     mgmt_net = None\n482:     if mgmt_passthrough:\n483:         mgmt_net = PassthroughRedirect([f\"udp:{TFTP_PORT}\", f\"udp:{'-'.join(map(str, TFTP_TID_RANGE))}\"])\n484:         mgmt_net.prep()\n485:         tftp_server = TFTPServer(mgmt_net=mgmt_net,\n486:                                  srv_port=TFTP_PORT,\n487:                                  tid_range=TFTP_TID_RANGE,\n488:                                  directory=TFTP_DIRECTORY)\n489:     else:\n490:         mgmt_net = HostForwardedBridge()\n491:         mgmt_net.prep()\n492:         tftp_server = TFTPServer(srv_port=TFTP_PORT,\n493:                                  mgmt_net=mgmt_net,\n494:                                  directory=TFTP_DIRECTORY)\n495: \n496:     vr = FortiOS(\n497:         args.hostname, args.username, args.password, conn_mode=args.connection_mode,\n498:         mgmt_net=mgmt_net, expected_product=expected_product\n499:     )\n500:     tftp_server.launch()\n501:     vrnetlab.boot_delay()\n502:     vr.start()\n503: \n504: \n505: if __name__ == \"__main__\":\n506:     main(get_env(\"FOS_EXPECTED_PRODUCT\", \"FortiGate\"))\n\n(End of file - total 506 lines)\n</content>",
    "title": "source/head/fortinet/common/launch.py",
    "metadata": {
      "preview": "logging.addLevelName(TRACE_LEVEL_NUM, \"\\x1b[1;35m\\tTRACE\\x1b[0m\")\nLOG_LEVEL_NAMES = {\n    \"TRACE\": TRACE_LEVEL_NUM,\n    \"DEBUG\": logging.DEBUG,\n    \"INFO\": logging.INFO,\n    \"WARN\": logging.WARN,\n    \"WARNING\": logging.WARNING,\n    \"ERROR\": logging.ERROR,\n    \"CRITICAL\": logging.CRITICAL,\n    \"FATAL\": logging.FATAL,\n}\n\n\ndef trace(self, message, *args, **kws):\n    # Yes, logger takes its '*args' as 'args'.\n    if self.isEnabledFor(TRACE_LEVEL_NUM):\n        self.log(TRACE_LEVEL_NUM, message, *args, **kws)\n\n\nlogging.Logger.trace = trace",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/launch.py",
        "text": "logging.addLevelName(TRACE_LEVEL_NUM, \"\\x1b[1;35m\\tTRACE\\x1b[0m\")\nLOG_LEVEL_NAMES = {\n    \"TRACE\": TRACE_LEVEL_NUM,\n    \"DEBUG\": logging.DEBUG,\n    \"INFO\": logging.INFO,\n    \"WARN\": logging.WARN,\n    \"WARNING\": logging.WARNING,\n    \"ERROR\": logging.ERROR,\n    \"CRITICAL\": logging.CRITICAL,\n    \"FATAL\": logging.FATAL,\n}\n\n\ndef trace(self, message, *args, **kws):\n    # Yes, logger takes its '*args' as 'args'.\n    if self.isEnabledFor(TRACE_LEVEL_NUM):\n        self.log(TRACE_LEVEL_NUM, message, *args, **kws)\n\n\nlogging.Logger.trace = trace\nMGMT_PASSTHROUGH_DEFAULT = True\nTFTP_PORT = 69\nTFTP_TID_RANGE = (52400, 52500)\nTFTP_DIRECTORY = \"/tftpboot\"\n\n\ndef parse_log_level(value):\n    if value is None or str(value).strip() == \"\":\n        return logging.DEBUG\n    value = str(value).strip()\n    try:\n        return int(value)\n    except ValueError:\n        pass\n    normalized = value.upper()\n    if normalized in LOG_LEVEL_NAMES:\n        return LOG_LEVEL_NAMES[normalized]\n    raise ValueError(\n        \"Invalid FOS_LOG_LEVEL. Use TRACE, DEBUG, INFO, WARN, ERROR, \"\n        \"another Python logging level name, or a numeric level.\"\n    )\n\n\ndef exit_on_bootstrap_error(value=None):\n    \"\"\"Return whether a bootstrap exception should terminate the VM.\n\n    Bootstrap failures are fatal by default.  The opt-out is intentionally\n    narrow: only the explicit value ``false`` disables termination, so a\n    misspelled or otherwise invalid value keeps the fail-fast behavior.\n    \"\"\"\n    if value is None:\n        value = get_env(\"FOS_EXIT_ON_BOOTSTRAP_ERROR\", \"true\")\n    return str(value).strip().lower() != \"false\"\n\n\ndef container_dns_servers(path=\"/etc/resolv.conf\"):\n    \"\"\"Return nameserver addresses configured for this container, in order.\"\"\"\n    try:\n        with open(path, encoding=\"utf-8\") as resolver_config:\n            servers = []\n            for line in resolver_config:\n                fields = line.split()\n                if len(fields) >= 2 and fields[0] == \"nameserver\":\n                    servers.append(fields[1])\n            return servers\n    except OSError:\n        return []\n\n\ndef apply_debug_feature_cutoff(features, stop_feature, logger):\n    \"\"\"Limit bootstrap features to those up to and including ``stop_feature``.\"\"\"\n    if stop_feature is None or str(stop_feature).strip() == \"\":\n        return features\n\n    stop_feature = str(stop_feature).strip()\n    for index, feature in enumerate(features):\n        if feature.name == stop_feature:\n            selected = features[:index + 1]\n            skipped = features[index + 1:]\n            logger.warning(\n                \"FOS_DEBUG_FEATURE=%s; stopping after feature %s. Skipping: %s\",\n                stop_feature,\n                stop_feature,\n                \", \".join(feature.name for feature in skipped) or \"(none)\",\n            )\n            return selected\n\n    available = \", \".join(feature.name for feature in features)\n    raise ValueError(f\"Unknown FOS_DEBUG_FEATURE '{stop_feature}'. Available features: {available}\")\n\n\nclass FortiOSConsole(vrnetlab._Console):\n    def __init__(self, driver):\n        super().__init__(driver)\n        self._output_enabled = True\n\n    def _read(self):\n        data = self._driver.channel.read()\n        if data and self._output_enabled:\n            sys.stdout.buffer.write(data)\n            sys.stdout.buffer.flush()\n        return data\n\n    def read_very_eager(self):\n        transport_socket = getattr(self._driver.transport, \"socket\", None)\n        socket = getattr(transport_socket, \"sock\", None)\n        if socket is not None:\n            readable, _, _ = select.select([socket], [], [], 0)\n            if not readable:\n                return b\"\"\n        return self._read()\n\n    def read_blocking(self):\n        return self._read()\n\n    @contextmanager\n    def suppress_output(self):\n        output_enabled = self._output_enabled\n        self._output_enabled = False\n        try:\n            yield\n        finally:\n            self._output_enabled = output_enabled\n\n\nclass FortiOS_vm(vrnetlab.VM):\n    def __init__(self, hostname: str, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n                 expected_product=\"FortiGate\"):\n        disk_image = None\n        for e in os.listdir(\".\"):\n            if re.search(\".qcow2$\", e):\n                disk_image = \"./\" + e\n        if disk_image is None:\n            raise RuntimeError(\"Could not find image to boot\")\n        super(FortiOS_vm, self).__init__(\n            username,\n            password,\n            disk_image=disk_image,\n            ram=2048,\n            driveif=\"virtio\",\n            # fortios fails to respond to network requests if the pci bus is setup :D\n            provision_pci_bus=False,\n            mgmt_passthrough=mgmt_net.mgmt_passthrough\n        )\n        self.tn = FortiOSConsole(self.scrapli_tn)\n\n        self.logger.info(f\"Launching. commandline: {' '.join(sys.argv)}\")\n        self.logger.warning(\"deploy --reconfigure, deploy --restore, redeploy, restart, restore, save, stop-then-start,\"\n                            \" not supported at this moment.\")\n        self.conn_mode = conn_mode\n        self.hostname = hostname\n        self.num_nics = 12\n        self.nic_type = \"virtio-net-pci\"\n        self.highest_port = 0\n        self.spins = 0\n        self.stopped = False\n        self._bootstrap_error = None\n        self._exit_on_bootstrap_error = exit_on_bootstrap_error()\n        self.waiting_for = False\n        self._mgmt_net = mgmt_net\n        self.expected_product = expected_product\n        self._mgmt_net.configure_vm_mgmt(self)\n        container_dns = container_dns_servers()\n        primary_dns = get_env(\n            \"FOS_MGMT_DNS_PRIMARY\",\n            aliases=(\"FTNT_DNS_PRIMARY\",),\n        )\n        secondary_dns = get_env(\n            \"FOS_MGMT_DNS_SECONDARY\",\n            aliases=(\"FTNT_DNS_SECONDARY\",),\n            legacy_aliases=(\"FTNT_MGMG_DNS_SECONDARY\", \"FOS_MGMG_DNS_SECONDARY\"),\n        )\n        if primary_dns is None:\n            primary_dns = container_dns[0] if container_dns else \"1.1.1.1\"\n        if secondary_dns is None:\n            secondary_dns = container_dns[1] if len(container_dns) > 1 else \"8.8.8.8\"\n        self.mgmt_dns_primary = primary_dns\n        self.mgmt_dns_secondary = secondary_dns\n        self.mgmt_dns_protocol = get_env(\"FTNT_DNS_PROTOCOL\", \"cleartext\")\n        self.terminal = Terminal(self.tn, self.logger, default_wait=self.wait_pattern)\n        desired_password = DEFAULT_PASSWORD if password is None else password\n        self._bootstrap_username = DEFAULT_USERNAME\n        self._bootstrap_password = DEF_POLICY_COMPLIANT_PASSWORD\n        self.credentials = Credentials(self._bootstrap_username, self._bootstrap_password)\n        self.desired_credentials = Credentials(username or DEFAULT_USERNAME, desired_password)\n        self.commander = FOSCommander(\n            terminal=self.terminal,\n            logger=self.logger,\n            continue_on_error=not self._exit_on_bootstrap_error,\n        )\n        self.fos_version = None\n        self.fos_product = None\n        self.driver = FOSCliDriver(\n            self.terminal,\n            self.commander,\n            self.credentials,\n            self.logger,\n            self._bootstrap_password,\n            self.activate_blank_credentials,\n            self.activate_bootstrap_credentials,\n            # Always retry the last accepted credentials after a desired\n            # password transition is rejected. The bootstrap error policy\n            # controls feature failures, not whether the console can recover.\n            allow_credential_recovery=True,\n        )\n        configure_dns = ConfigureMgmtDns(self, self.commander)\n        license_validation = WaitForLicenseValidation(self, self.commander)\n        self._features = [\n            ImageInfo(self, self.commander),\n            ValidateProduct(self, self.commander, expected_product),\n            FormatDisks(self, self.commander),\n            CredentialsFeature(self, self.commander),\n            ConfigureMgmtNetwork(self, self.commander),\n            configure_dns,\n            ConfigureFortiGuardHooks(self, self.commander),\n            SetLicense(self, self.commander),\n            ReapplyFortiGuardHooks(self, self.commander),\n            DefaultConfig(self, self.commander),\n            ReconfigureMgmtNetwork(self, self.commander),\n            license_validation,\n            WaitForFortiTokens(self, self.commander, license_validation),\n            InstallPkiCertificates(self, self.commander),\n            MoveMgmtToVrf1(self, self.commander),\n            ConfigSaveFeature(self, self.commander),\n            ApplyStartupConfig(self, self.commander),\n        ]\n        self._features = apply_debug_feature_cutoff(\n            self._features,\n            get_env(\"FOS_DEBUG_FEATURE\"),\n            self.logger,\n        )\n        self._file_watcher = FeatureFileWatcher(self._features, self.logger)\n        self.commander.start(self._features)\n        vrnetlab.run_command(\n            [\"qemu-img\", \"create\", \"-f\", \"qcow2\", \"empty.qcow2\", \"30G\"]\n        )\n\n        # Comma-separated list of disk sizes to install in the machine. as accepted by qemu-img create.\n        disk_specs = get_env(\"FOS_DISK_SPECS\", \"\").split(\",\")\n        if disk_specs[0] == '':\n            self.logger.warning(\n                \"No additional disks configured. Use FOS_DISK_SPECS to specify a comma-separated list of disk sizes\")\n            return\n        index = 0\n        for spec in disk_specs:\n            index += 1\n            # set up the extra empty disk image\n            # for fortigate logs\n            vrnetlab.run_command(\n                [\"qemu-img\", \"create\", \"-f\", \"qcow2\", f\"empty{index}.qcow2\", spec]\n            )\n\n            self.qemu_args.extend(\n                [\n                    \"-drive\",\n                    f\"if=virtio,format=qcow2,file=empty{index}.qcow2,index={index}\",\n                ]\n            )\n\n            index += 1\n\n    def bootstrap_spin(self):\n        \"\"\"This function should be called periodically to do work.\n\n        returns False when it has failed and given up, otherwise True\n        \"\"\"\n        if self._bootstrap_error is not None:\n            return False\n        try:\n            self.driver.process_state()\n        except KernelPanicError:\n            self.stop()\n            raise\n        except Exception as error:\n            if self._exit_on_bootstrap_error or self.commander.startup_complete:\n                self.stop()\n                raise\n            failed_work = self.commander.continue_after_error(\n                error,\n                at_command_prompt=self.driver.at_command_prompt,\n            )\n            if failed_work is not None:\n                self.logger.exception(\n                    \"Bootstrap work %s failed; continuing with remaining features \"\n                    \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n                    failed_work,\n                )\n                return True\n            self._bootstrap_error = error\n            self.logger.exception(\n                \"Bootstrap cannot continue safely; keeping the VM running for manual \"\n                \"repair because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\"\n            )\n            try:\n                self.terminal.close()\n                self.logger.info(\n                    \"Released the launcher's serial Telnet connection after bootstrap stopped\"\n                )\n            except Exception:\n                self.logger.exception(\n                    \"Failed to release the serial Telnet connection after bootstrap stopped\"\n                )\n            return False\n        if self.driver.ready and not self.commander.feature_errors:\n            self.running = True\n        return True\n\n    def work(self):\n        self._write_heartbeat()\n        super().work()\n        if self.running:\n            self._file_watcher.poll()\n            if not self.driver.ready:\n                self.bootstrap_spin()\n\n    def _write_heartbeat(self):\n        \"\"\"Append one byte to the healthcheck heartbeat file.\n\n        ``fos_healthcheck.py`` blocks in \"starting\" as long as this file\n        keeps growing, so a slow but progressing bootstrap never trips the\n        Docker unhealthy threshold. A wedged launcher stops beating and the\n        probe reports failure. Best-effort: a heartbeat write must never\n        take down the main loop.\n        \"\"\"\n        try:\n            with open(HEARTBEAT_FILE, \"a\") as heartbeat_handle:\n                heartbeat_handle.write(\"\\n\")\n        except OSError:\n            self.logger.debug(\"Failed to write healthcheck heartbeat\", exc_info=True)\n\n    def connect_serial_console(self):\n        try:\n            self.terminal.close()\n        except Exception:\n            pass\n\n        for attempt in range(1, vrnetlab.MAX_RETRIES + 1):\n            try:\n                self.tn.open()\n                break\n            except Exception:\n                if attempt == vrnetlab.MAX_RETRIES:\n                    self.logger.exception(\"Failed to connect to VM serial port.\")\n                    self.stop()\n                    raise\n                self.logger.error(\n                    f\"Unable to connect to VM serial port {5000 + self.num}, \"\n                    f\"retrying in a second (attempt {attempt})\"\n                )\n                time.sleep(1)\n\n        self.stopped = False\n        self.terminal.write(b\"\\r\")\n\n    def activate_desired_credentials(self):\n        self.driver.remember_current_credentials()\n        self.credentials.username = self.desired_credentials.username\n        self.credentials.password = self.desired_credentials.password\n\n    def activate_bootstrap_credentials(self):\n        self.credentials.username = self._bootstrap_username\n        self.credentials.password = self._bootstrap_password\n\n    def activate_blank_credentials(self):\n        self.credentials.password = \"\"\n\n    def gen_mgmt(self):\n        return self._mgmt_net.gen_mgmt(self)\n\n    @staticmethod\n    def mgmt_gateway_destination(gateway, mgmt_address):\n        _address, separator, prefix = str(mgmt_address).partition(\"/\")\n        if separator and prefix:\n            return f\"{gateway}/{prefix}\"\n        return f\"{gateway}/{'128' if ':' in str(gateway) else '32'}\"\n\n    def stop(self):\n        self.stopped = True\n        super().stop()\n\n\nclass FortiOS(vrnetlab.VR):\n    def __init__(self, hostname, username, password, conn_mode, mgmt_net: NetMgmtStrategy,\n                 expected_product=\"FortiGate\"):\n        super(FortiOS, self).__init__(username, password, mgmt_passthrough=mgmt_net.mgmt_passthrough)\n        self.logger.debug(\"Hostname\")\n        self.logger.debug(hostname)\n        self.vms = [FortiOS_vm(hostname, username, password, conn_mode, mgmt_net=mgmt_net,\n                               expected_product=expected_product)]\n\n\ndef main(expected_product=\"FortiGate\"):\n\n    parser = argparse.ArgumentParser(description=\"\")\n    parser.add_argument(\n        \"--trace\", action=\"store_true\", help=\"enable trace level logging\"\n    )\n    parser.add_argument(\"--hostname\", default=\"vr-fortinet\", help=\"Fortinet hostname\")\n    parser.add_argument(\"--username\", default=None, help=\"Username\")\n    parser.add_argument(\"--password\", default=None, help=\"Password\", nargs=\"?\")\n    parser.add_argument(\n        \"--connection-mode\",\n        default=\"tc\",\n        help=\"Connection mode to use in the datapath\",\n    )\n    args = parser.parse_args()\n\n    LOG_FORMAT = \"%(asctime)s: %(module)-10s %(levelname)-8s %(message)s\"\n    logging.basicConfig(format=LOG_FORMAT)\n    logger = logging.getLogger()\n\n    logger.setLevel(parse_log_level(get_env(\"FOS_LOG_LEVEL\")))\n\n    mgmt_passthrough = (\n        os.environ.get(\"CLAB_MGMT_PASSTHROUGH\", \"\").lower() == \"true\"\n        if os.environ.get(\"CLAB_MGMT_PASSTHROUGH\")\n        else MGMT_PASSTHROUGH_DEFAULT\n    )\n\n    tftp_server = None\n    mgmt_net = None\n    if mgmt_passthrough:\n        mgmt_net = PassthroughRedirect([f\"udp:{TFTP_PORT}\", f\"udp:{'-'.join(map(str, TFTP_TID_RANGE))}\"])\n        mgmt_net.prep()\n        tftp_server = TFTPServer(mgmt_net=mgmt_net,\n                                 srv_port=TFTP_PORT,\n                                 tid_range=TFTP_TID_RANGE,\n                                 directory=TFTP_DIRECTORY)\n    else:\n        mgmt_net = HostForwardedBridge()\n        mgmt_net.prep()\n        tftp_server = TFTPServer(srv_port=TFTP_PORT,\n                                 mgmt_net=mgmt_net,\n                                 directory=TFTP_DIRECTORY)\n\n    vr = FortiOS(\n        args.hostname, args.username, args.password, conn_mode=args.connection_mode,\n        mgmt_net=mgmt_net, expected_product=expected_product\n    )\n    tftp_server.launch()\n    vrnetlab.boot_delay()\n    vr.start()\n\n\nif __name__ == \"__main__\":\n    main(get_env(\"FOS_EXPECTED_PRODUCT\", \"FortiGate\"))",
        "lineStart": 61,
        "lineEnd": 506,
        "totalLines": 506,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716548247,
      "end": 1793716548251
    }
  }
}
read · error

Input

{
  "filePath": "/source/head/fortinet/common/common.py",
  "offset": 120
}

Output

Offset 120 is out of range for this file (92 lines)
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d672d8001TQbzaO2mw1hjE9",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6670200104Gc8tYpgFupal",
  "callID": "call_2d184be276d24562ba5d4d97",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/head/fortinet/common/common.py",
      "offset": 120
    },
    "error": "Offset 120 is out of range for this file (92 lines)",
    "time": {
      "start": 1793716548316,
      "end": 1793716548322
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d672e4001z11fv6DvFqE73Y",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6670200104Gc8tYpgFupal",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 17186,
    "input": 8009,
    "output": 112,
    "reasoning": 105,
    "cache": {
      "read": 8960,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d6670200104Gc8tYpgFupal",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716545283,
    "completed": 1793716548326
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 17186,
    "input": 8009,
    "output": 112,
    "reasoning": 105,
    "cache": {
      "read": 8960,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 26
step-start
{
  "type": "step-start",
  "id": "prt_1a1d678c90010gkWnYBOZxfHOk",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d672ec0016X1lLBjAUdzQBg"
}
Reasoning
common.py is only 92 lines? Wait, earlier I read first 120 lines and saw TRACE_LEVEL, FOSCliState, BOOTSTRAP_HOSTNAME_REGEX, PROMPT_CONTEXT_REGEX... Actually wait, earlier summary said "common.py first 120 lines (TRACE_LEVEL=9, FOSCliState enum ...)". But now file is 92 lines total. Hmm — maybe I read common.py in fortinet/common/ and it's 92 lines. The earlier summary mentioned reading first 120 lines but the file is 92 lines. Either way, common.py is fully read now (92 lines < 120). Fine.

Now remaining: features/license.py (rest), features/credentials.py (rest), features/pki.py, features/startup_config.py (done), and the tests + READMEs.

Let me read license.py, credentials.py, pki.py fully, and test_common_stack_boundaries.py.
`common.py` is fully read (92 lines). Now the remaining feature files and the boundaries test file.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/license.py"
}

Output

<path>/source/head/fortinet/common/features/license.py</path>
<type>file</type>
<content>
1: """VM license installation feature."""
2: 
3: import os
4: import re
5: import time
6: 
7: from ..cli_commands import CommandSequence, CommandSpec, SessionLossAction
8: from ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState
9: from ..env import get_env
10: 
11: from .base import Feature
12: 
13: 
14: DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60
15: LICENSE_STATUS_POLL_INTERVAL_SECONDS = 2
16: LICENSE_SETTLE_SECONDS = 3
17: LICENSE_WAIT_STATUSES = {"pending"}
18: LICENSE_GRACE_PERIOD_STATUS = "grace period"
19: LOG_LICENSE_STATUS_OUTPUT_ENV = "FOS_LOG_LICENSE_STATUS_OUTPUT"
20: 
21: # FortiOS does not print a single success message for "execute restore
22: # vmlicense"; the only failure signature is "license install failed"
23: # (e.g. "VM license install failed."). Everything else is success.
24: LICENSE_FAILURE_PATTERN = re.compile(rb"(?mi)license install failed")
25: 
26: 
27: def license_status_timeout_seconds():
28:     value = get_env("FOS_LICENSE_STATUS_TIMEOUT_SECONDS")
29:     if not value:
30:         return DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS
31:     return int(value)
32: 
33: 
34: def wait_for_valid_license():
35:     return get_env("FOS_WAIT_FOR_VALID_LICENSE", "false").strip().lower() == "true"
36: 
37: 
38: class SetLicense(Feature):
39:     """Install a license without waiting for online validation.
40: 
41:     FortiOS license restore reboots the VM and can reset parts of management
42:     networking.  Online validation must be polled only after post-license
43:     management repair has run.
44:     """
45: 
46:     def __init__(self, vm, commander):
47:         super().__init__(vm, commander, "setup-license")
48:         self._enabled = os.path.exists("/tftpboot/appliance.lic")
49:         self._tftp_server_ip = vm.mgmt_gw_ipv4
50:         self._phase = "restore"
51:         self._wait_for_prompt = False
52: 
53:     def activate(self):
54:         if not self._enabled:
55:             self.commander.feature_complete(self)
56:             return
57:         self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)
58:         self._submit_restore()
59: 
60:     def _submit_restore(self):
61:         # CMD_PROMPT must complete the restore too: when the install fails
62:         # FortiOS prints the failure and returns to the prompt without ever
63:         # asking for confirmation, which would otherwise wedge the block.
64:         self.commander.submit_block(self, CommandSequence("restore-license", [
65:             CommandSpec(
66:                 f"exe restore vmlicense tftp appliance.lic {self._tftp_server_ip}",
67:                 completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),
68:                 capture_output=True,
69:                 session_loss=SessionLossAction.CONTINUE,
70:             ),
71:         ]))
72: 
73:     def on_command_executed(self, command, state):
74:         self._check_for_failure(command)
75:         if self._phase == "restore" and state == FOSCliState.CONFIRMATION:
76:             self._phase = "restore-confirmed"
77:             self.commander.submit_block(self, CommandSequence("confirm-license", [
78:                 CommandSpec(
79:                     "y",
80:                     completion_states=(FOSCliState.REBOOTING,),
81:                     session_loss=SessionLossAction.CONTINUE,
82:                 ),
83:             ]))
84:             return
85:         if self._phase == "restore-confirmed" and state == FOSCliState.REBOOTING:
86:             self._phase = "wait-prompt"
87:             self._wait_for_prompt = True
88:             return
89:         # The restore completed somewhere other than the confirmation
90:         # prompt (a plain prompt instead): the install failed before
91:         # confirmation. The failure check above already raised on a "fail"
92:         # word, so fall through to wait-prompt rather than wedging the
93:         # block.
94:         self._phase = "wait-prompt"
95:         self._wait_for_prompt = True
96: 
97:     def on_output(self, output):
98:         """Raise on a failure reported while a license command runs.
99: 
100:         The confirmation is completed by the reboot, not by the command
101:         prompt that returns right after "y" and before the reboot starts, so
102:         a failed install would otherwise only surface once the command
103:         completed. Watch the streaming output instead.
104:         """
105:         if self._phase in ("restore", "restore-confirmed"):
106:             output = bytes(output)
107:             if LICENSE_FAILURE_PATTERN.search(output):
108:                 raise RuntimeError(
109:                     f"VM license install failed: {output!r}"
110:                 )
111:         return False
112: 
113:     def _check_for_failure(self, command):
114:         output = bytes(command.output)
115:         if LICENSE_FAILURE_PATTERN.search(output):
116:             raise RuntimeError(
117:                 f"VM license install failed: {output!r}"
118:             )
119: 
120:     def on_block_complete(self):
121:         if self._phase in ("restore", "restore-confirmed"):
122:             return
123:         if self._phase == "wait-prompt":
124:             if self._wait_for_prompt:
125:                 self._wait_for_prompt = False
126:                 return
127:             self._phase = "done"
128:         if self._phase == "done":
129:             self.commander.feature_complete(self)
130: 
131:     def on_session_loss(self, attempt):
132:         if attempt.spec.session_loss == SessionLossAction.CONTINUE:
133:             self._phase = "wait-prompt"
134:             self._wait_for_prompt = True
135:         return attempt.spec.session_loss
136: 
137: 
138: class WaitForLicenseValidation(Feature):
139:     """Poll FortiOS until the restored license validates or times out."""
140: 
141:     def __init__(self, vm, commander):
142:         super().__init__(vm, commander, "license-validation")
143:         self._enabled = os.path.exists("/tftpboot/appliance.lic")
144:         self._logger = commander.logger
145:         self._deadline = None
146:         self._next_poll = None
147:         self._phase = "idle"
148:         self._status = None
149:         self._status_outputs_logged = set()
150:         self._standard_output_active = False
151:         self._settle_until = 0
152: 
153:     @property
154:     def status(self):
155:         return self._status
156: 
157:     @property
158:     def valid(self):
159:         return self._status is not None and self._status.lower() == "valid"
160: 
161:     def activate(self):
162:         if not self._enabled:
163:             self.commander.feature_complete(self)
164:             return
165:         self._deadline = time.monotonic() + license_status_timeout_seconds()
166:         self._phase = "polling"
167:         self._next_poll = time.monotonic()
168: 
169:     def on_command_executed(self, command, state):
170:         output = bytes(command.output)
171:         status = self._license_status(output)
172:         self._log_status_output(output, status)
173:         normalized_status = status.lower() if status else None
174:         if (
175:             not status
176:             or normalized_status in LICENSE_WAIT_STATUSES
177:             or (
178:                 normalized_status == LICENSE_GRACE_PERIOD_STATUS
179:                 and wait_for_valid_license()
180:             )
181:         ):
182:             previous_status = self._status.lower() if self._status else None
183:             self._status = status
184:             if normalized_status != previous_status:
185:                 self._logger.info(
186:                     "License status is %s; continuing validation polls",
187:                     status or "unavailable",
188:                 )
189:             if time.monotonic() >= self._deadline:
190:                 raise RuntimeError(
191:                     "VM license validation timed out with status "
192:                     f"{status or 'unavailable'}"
193:                 )
194:             self._next_poll = time.monotonic() + LICENSE_STATUS_POLL_INTERVAL_SECONDS
195:             return
196:         self._status = status
197:         if normalized_status == LICENSE_GRACE_PERIOD_STATUS:
198:             self._logger.info(
199:                 "Accepting license status %s without waiting for Valid",
200:                 status,
201:             )
202:             self._finish_validation()
203:             return
204:         if status.lower() != "valid":
205:             raise RuntimeError(
206:                 f"VM license validation failed: status {status}"
207:             )
208:         self._logger.info(f"License status changed to {status}")
209:         self._finish_validation()
210: 
211:     def _finish_validation(self):
212:         self._phase = "done"
213:         self._settle_until = time.monotonic() + LICENSE_SETTLE_SECONDS
214: 
215:     @staticmethod
216:     def _license_status(output):
217:         match = re.search(rb"(?mi)^License Status:\s*(.+?)\s*\r?$", output)
218:         if not match:
219:             match = re.search(rb"(?mi)^License:\s*(.+?)\s*\r?$", output)
220:         return match.group(1).decode(errors="replace").strip() if match else None
221: 
222:     def _log_status_output(self, output, status):
223:         if get_env(
224:             LOG_LICENSE_STATUS_OUTPUT_ENV, "false"
225:         ).strip().lower() != "true":
226:             return
227:         normalized_status = status.lower() if status else None
228:         if normalized_status in self._status_outputs_logged:
229:             return
230:         self._status_outputs_logged.add(normalized_status)
231:         self._logger.info(
232:             "Captured get system status output for license status %s:\n%s",
233:             status or "unavailable",
234:             output.decode(errors="replace").rstrip(),
235:         )
236: 
237:     def on_block_complete(self):
238:         if self._phase != "done":
239:             return
240:         if time.monotonic() < self._settle_until:
241:             return
242:         self.commander.feature_complete(self)
243: 
244:     def tick(self):
245:         now = time.monotonic()
246:         if self._phase == "done":
247:             if now >= self._settle_until:
248:                 self.commander.feature_complete(self)
249:             return
250:         if self._phase != "polling" or self._next_poll is None:
251:             return
252:         if now >= self._deadline:
253:             raise RuntimeError(
254:                 "VM license validation timed out with status "
255:                 f"{self._status or 'unavailable'}"
256:             )
257:         if now >= self._next_poll and not self.commander.busy:
258:             self._next_poll = None
259:             if self._standard_output_active:
260:                 self._submit_status_poll()
261:             else:
262:                 self._standard_output_active = True
263:                 self.commander.with_standard_output(self, self._submit_status_poll)
264: 
265:     def _submit_status_poll(self):
266:         self.commander.submit_block(self, CommandSequence("license-validation", [
267:             CommandSpec("get system status", capture_output=True, suppress_output=True),
268:         ]))

(End of file - total 268 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d67e77001KMq6DSzJuCPLvR",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d672ec0016X1lLBjAUdzQBg",
  "callID": "call_9a8cfe00b48b4a1c8258a965",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/license.py"
    },
    "output": "<path>/source/head/fortinet/common/features/license.py</path>\n<type>file</type>\n<content>\n1: \"\"\"VM license installation feature.\"\"\"\n2: \n3: import os\n4: import re\n5: import time\n6: \n7: from ..cli_commands import CommandSequence, CommandSpec, SessionLossAction\n8: from ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState\n9: from ..env import get_env\n10: \n11: from .base import Feature\n12: \n13: \n14: DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60\n15: LICENSE_STATUS_POLL_INTERVAL_SECONDS = 2\n16: LICENSE_SETTLE_SECONDS = 3\n17: LICENSE_WAIT_STATUSES = {\"pending\"}\n18: LICENSE_GRACE_PERIOD_STATUS = \"grace period\"\n19: LOG_LICENSE_STATUS_OUTPUT_ENV = \"FOS_LOG_LICENSE_STATUS_OUTPUT\"\n20: \n21: # FortiOS does not print a single success message for \"execute restore\n22: # vmlicense\"; the only failure signature is \"license install failed\"\n23: # (e.g. \"VM license install failed.\"). Everything else is success.\n24: LICENSE_FAILURE_PATTERN = re.compile(rb\"(?mi)license install failed\")\n25: \n26: \n27: def license_status_timeout_seconds():\n28:     value = get_env(\"FOS_LICENSE_STATUS_TIMEOUT_SECONDS\")\n29:     if not value:\n30:         return DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS\n31:     return int(value)\n32: \n33: \n34: def wait_for_valid_license():\n35:     return get_env(\"FOS_WAIT_FOR_VALID_LICENSE\", \"false\").strip().lower() == \"true\"\n36: \n37: \n38: class SetLicense(Feature):\n39:     \"\"\"Install a license without waiting for online validation.\n40: \n41:     FortiOS license restore reboots the VM and can reset parts of management\n42:     networking.  Online validation must be polled only after post-license\n43:     management repair has run.\n44:     \"\"\"\n45: \n46:     def __init__(self, vm, commander):\n47:         super().__init__(vm, commander, \"setup-license\")\n48:         self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n49:         self._tftp_server_ip = vm.mgmt_gw_ipv4\n50:         self._phase = \"restore\"\n51:         self._wait_for_prompt = False\n52: \n53:     def activate(self):\n54:         if not self._enabled:\n55:             self.commander.feature_complete(self)\n56:             return\n57:         self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)\n58:         self._submit_restore()\n59: \n60:     def _submit_restore(self):\n61:         # CMD_PROMPT must complete the restore too: when the install fails\n62:         # FortiOS prints the failure and returns to the prompt without ever\n63:         # asking for confirmation, which would otherwise wedge the block.\n64:         self.commander.submit_block(self, CommandSequence(\"restore-license\", [\n65:             CommandSpec(\n66:                 f\"exe restore vmlicense tftp appliance.lic {self._tftp_server_ip}\",\n67:                 completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),\n68:                 capture_output=True,\n69:                 session_loss=SessionLossAction.CONTINUE,\n70:             ),\n71:         ]))\n72: \n73:     def on_command_executed(self, command, state):\n74:         self._check_for_failure(command)\n75:         if self._phase == \"restore\" and state == FOSCliState.CONFIRMATION:\n76:             self._phase = \"restore-confirmed\"\n77:             self.commander.submit_block(self, CommandSequence(\"confirm-license\", [\n78:                 CommandSpec(\n79:                     \"y\",\n80:                     completion_states=(FOSCliState.REBOOTING,),\n81:                     session_loss=SessionLossAction.CONTINUE,\n82:                 ),\n83:             ]))\n84:             return\n85:         if self._phase == \"restore-confirmed\" and state == FOSCliState.REBOOTING:\n86:             self._phase = \"wait-prompt\"\n87:             self._wait_for_prompt = True\n88:             return\n89:         # The restore completed somewhere other than the confirmation\n90:         # prompt (a plain prompt instead): the install failed before\n91:         # confirmation. The failure check above already raised on a \"fail\"\n92:         # word, so fall through to wait-prompt rather than wedging the\n93:         # block.\n94:         self._phase = \"wait-prompt\"\n95:         self._wait_for_prompt = True\n96: \n97:     def on_output(self, output):\n98:         \"\"\"Raise on a failure reported while a license command runs.\n99: \n100:         The confirmation is completed by the reboot, not by the command\n101:         prompt that returns right after \"y\" and before the reboot starts, so\n102:         a failed install would otherwise only surface once the command\n103:         completed. Watch the streaming output instead.\n104:         \"\"\"\n105:         if self._phase in (\"restore\", \"restore-confirmed\"):\n106:             output = bytes(output)\n107:             if LICENSE_FAILURE_PATTERN.search(output):\n108:                 raise RuntimeError(\n109:                     f\"VM license install failed: {output!r}\"\n110:                 )\n111:         return False\n112: \n113:     def _check_for_failure(self, command):\n114:         output = bytes(command.output)\n115:         if LICENSE_FAILURE_PATTERN.search(output):\n116:             raise RuntimeError(\n117:                 f\"VM license install failed: {output!r}\"\n118:             )\n119: \n120:     def on_block_complete(self):\n121:         if self._phase in (\"restore\", \"restore-confirmed\"):\n122:             return\n123:         if self._phase == \"wait-prompt\":\n124:             if self._wait_for_prompt:\n125:                 self._wait_for_prompt = False\n126:                 return\n127:             self._phase = \"done\"\n128:         if self._phase == \"done\":\n129:             self.commander.feature_complete(self)\n130: \n131:     def on_session_loss(self, attempt):\n132:         if attempt.spec.session_loss == SessionLossAction.CONTINUE:\n133:             self._phase = \"wait-prompt\"\n134:             self._wait_for_prompt = True\n135:         return attempt.spec.session_loss\n136: \n137: \n138: class WaitForLicenseValidation(Feature):\n139:     \"\"\"Poll FortiOS until the restored license validates or times out.\"\"\"\n140: \n141:     def __init__(self, vm, commander):\n142:         super().__init__(vm, commander, \"license-validation\")\n143:         self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n144:         self._logger = commander.logger\n145:         self._deadline = None\n146:         self._next_poll = None\n147:         self._phase = \"idle\"\n148:         self._status = None\n149:         self._status_outputs_logged = set()\n150:         self._standard_output_active = False\n151:         self._settle_until = 0\n152: \n153:     @property\n154:     def status(self):\n155:         return self._status\n156: \n157:     @property\n158:     def valid(self):\n159:         return self._status is not None and self._status.lower() == \"valid\"\n160: \n161:     def activate(self):\n162:         if not self._enabled:\n163:             self.commander.feature_complete(self)\n164:             return\n165:         self._deadline = time.monotonic() + license_status_timeout_seconds()\n166:         self._phase = \"polling\"\n167:         self._next_poll = time.monotonic()\n168: \n169:     def on_command_executed(self, command, state):\n170:         output = bytes(command.output)\n171:         status = self._license_status(output)\n172:         self._log_status_output(output, status)\n173:         normalized_status = status.lower() if status else None\n174:         if (\n175:             not status\n176:             or normalized_status in LICENSE_WAIT_STATUSES\n177:             or (\n178:                 normalized_status == LICENSE_GRACE_PERIOD_STATUS\n179:                 and wait_for_valid_license()\n180:             )\n181:         ):\n182:             previous_status = self._status.lower() if self._status else None\n183:             self._status = status\n184:             if normalized_status != previous_status:\n185:                 self._logger.info(\n186:                     \"License status is %s; continuing validation polls\",\n187:                     status or \"unavailable\",\n188:                 )\n189:             if time.monotonic() >= self._deadline:\n190:                 raise RuntimeError(\n191:                     \"VM license validation timed out with status \"\n192:                     f\"{status or 'unavailable'}\"\n193:                 )\n194:             self._next_poll = time.monotonic() + LICENSE_STATUS_POLL_INTERVAL_SECONDS\n195:             return\n196:         self._status = status\n197:         if normalized_status == LICENSE_GRACE_PERIOD_STATUS:\n198:             self._logger.info(\n199:                 \"Accepting license status %s without waiting for Valid\",\n200:                 status,\n201:             )\n202:             self._finish_validation()\n203:             return\n204:         if status.lower() != \"valid\":\n205:             raise RuntimeError(\n206:                 f\"VM license validation failed: status {status}\"\n207:             )\n208:         self._logger.info(f\"License status changed to {status}\")\n209:         self._finish_validation()\n210: \n211:     def _finish_validation(self):\n212:         self._phase = \"done\"\n213:         self._settle_until = time.monotonic() + LICENSE_SETTLE_SECONDS\n214: \n215:     @staticmethod\n216:     def _license_status(output):\n217:         match = re.search(rb\"(?mi)^License Status:\\s*(.+?)\\s*\\r?$\", output)\n218:         if not match:\n219:             match = re.search(rb\"(?mi)^License:\\s*(.+?)\\s*\\r?$\", output)\n220:         return match.group(1).decode(errors=\"replace\").strip() if match else None\n221: \n222:     def _log_status_output(self, output, status):\n223:         if get_env(\n224:             LOG_LICENSE_STATUS_OUTPUT_ENV, \"false\"\n225:         ).strip().lower() != \"true\":\n226:             return\n227:         normalized_status = status.lower() if status else None\n228:         if normalized_status in self._status_outputs_logged:\n229:             return\n230:         self._status_outputs_logged.add(normalized_status)\n231:         self._logger.info(\n232:             \"Captured get system status output for license status %s:\\n%s\",\n233:             status or \"unavailable\",\n234:             output.decode(errors=\"replace\").rstrip(),\n235:         )\n236: \n237:     def on_block_complete(self):\n238:         if self._phase != \"done\":\n239:             return\n240:         if time.monotonic() < self._settle_until:\n241:             return\n242:         self.commander.feature_complete(self)\n243: \n244:     def tick(self):\n245:         now = time.monotonic()\n246:         if self._phase == \"done\":\n247:             if now >= self._settle_until:\n248:                 self.commander.feature_complete(self)\n249:             return\n250:         if self._phase != \"polling\" or self._next_poll is None:\n251:             return\n252:         if now >= self._deadline:\n253:             raise RuntimeError(\n254:                 \"VM license validation timed out with status \"\n255:                 f\"{self._status or 'unavailable'}\"\n256:             )\n257:         if now >= self._next_poll and not self.commander.busy:\n258:             self._next_poll = None\n259:             if self._standard_output_active:\n260:                 self._submit_status_poll()\n261:             else:\n262:                 self._standard_output_active = True\n263:                 self.commander.with_standard_output(self, self._submit_status_poll)\n264: \n265:     def _submit_status_poll(self):\n266:         self.commander.submit_block(self, CommandSequence(\"license-validation\", [\n267:             CommandSpec(\"get system status\", capture_output=True, suppress_output=True),\n268:         ]))\n\n(End of file - total 268 lines)\n</content>",
    "title": "source/head/fortinet/common/features/license.py",
    "metadata": {
      "preview": "\"\"\"VM license installation feature.\"\"\"\n\nimport os\nimport re\nimport time\n\nfrom ..cli_commands import CommandSequence, CommandSpec, SessionLossAction\nfrom ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState\nfrom ..env import get_env\n\nfrom .base import Feature\n\n\nDEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60\nLICENSE_STATUS_POLL_INTERVAL_SECONDS = 2\nLICENSE_SETTLE_SECONDS = 3\nLICENSE_WAIT_STATUSES = {\"pending\"}\nLICENSE_GRACE_PERIOD_STATUS = \"grace period\"\nLOG_LICENSE_STATUS_OUTPUT_ENV = \"FOS_LOG_LICENSE_STATUS_OUTPUT\"\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/license.py",
        "text": "\"\"\"VM license installation feature.\"\"\"\n\nimport os\nimport re\nimport time\n\nfrom ..cli_commands import CommandSequence, CommandSpec, SessionLossAction\nfrom ..common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState\nfrom ..env import get_env\n\nfrom .base import Feature\n\n\nDEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS = 2 * 60\nLICENSE_STATUS_POLL_INTERVAL_SECONDS = 2\nLICENSE_SETTLE_SECONDS = 3\nLICENSE_WAIT_STATUSES = {\"pending\"}\nLICENSE_GRACE_PERIOD_STATUS = \"grace period\"\nLOG_LICENSE_STATUS_OUTPUT_ENV = \"FOS_LOG_LICENSE_STATUS_OUTPUT\"\n\n# FortiOS does not print a single success message for \"execute restore\n# vmlicense\"; the only failure signature is \"license install failed\"\n# (e.g. \"VM license install failed.\"). Everything else is success.\nLICENSE_FAILURE_PATTERN = re.compile(rb\"(?mi)license install failed\")\n\n\ndef license_status_timeout_seconds():\n    value = get_env(\"FOS_LICENSE_STATUS_TIMEOUT_SECONDS\")\n    if not value:\n        return DEFAULT_LICENSE_STATUS_TIMEOUT_SECONDS\n    return int(value)\n\n\ndef wait_for_valid_license():\n    return get_env(\"FOS_WAIT_FOR_VALID_LICENSE\", \"false\").strip().lower() == \"true\"\n\n\nclass SetLicense(Feature):\n    \"\"\"Install a license without waiting for online validation.\n\n    FortiOS license restore reboots the VM and can reset parts of management\n    networking.  Online validation must be polled only after post-license\n    management repair has run.\n    \"\"\"\n\n    def __init__(self, vm, commander):\n        super().__init__(vm, commander, \"setup-license\")\n        self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n        self._tftp_server_ip = vm.mgmt_gw_ipv4\n        self._phase = \"restore\"\n        self._wait_for_prompt = False\n\n    def activate(self):\n        if not self._enabled:\n            self.commander.feature_complete(self)\n            return\n        self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)\n        self._submit_restore()\n\n    def _submit_restore(self):\n        # CMD_PROMPT must complete the restore too: when the install fails\n        # FortiOS prints the failure and returns to the prompt without ever\n        # asking for confirmation, which would otherwise wedge the block.\n        self.commander.submit_block(self, CommandSequence(\"restore-license\", [\n            CommandSpec(\n                f\"exe restore vmlicense tftp appliance.lic {self._tftp_server_ip}\",\n                completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),\n                capture_output=True,\n                session_loss=SessionLossAction.CONTINUE,\n            ),\n        ]))\n\n    def on_command_executed(self, command, state):\n        self._check_for_failure(command)\n        if self._phase == \"restore\" and state == FOSCliState.CONFIRMATION:\n            self._phase = \"restore-confirmed\"\n            self.commander.submit_block(self, CommandSequence(\"confirm-license\", [\n                CommandSpec(\n                    \"y\",\n                    completion_states=(FOSCliState.REBOOTING,),\n                    session_loss=SessionLossAction.CONTINUE,\n                ),\n            ]))\n            return\n        if self._phase == \"restore-confirmed\" and state == FOSCliState.REBOOTING:\n            self._phase = \"wait-prompt\"\n            self._wait_for_prompt = True\n            return\n        # The restore completed somewhere other than the confirmation\n        # prompt (a plain prompt instead): the install failed before\n        # confirmation. The failure check above already raised on a \"fail\"\n        # word, so fall through to wait-prompt rather than wedging the\n        # block.\n        self._phase = \"wait-prompt\"\n        self._wait_for_prompt = True\n\n    def on_output(self, output):\n        \"\"\"Raise on a failure reported while a license command runs.\n\n        The confirmation is completed by the reboot, not by the command\n        prompt that returns right after \"y\" and before the reboot starts, so\n        a failed install would otherwise only surface once the command\n        completed. Watch the streaming output instead.\n        \"\"\"\n        if self._phase in (\"restore\", \"restore-confirmed\"):\n            output = bytes(output)\n            if LICENSE_FAILURE_PATTERN.search(output):\n                raise RuntimeError(\n                    f\"VM license install failed: {output!r}\"\n                )\n        return False\n\n    def _check_for_failure(self, command):\n        output = bytes(command.output)\n        if LICENSE_FAILURE_PATTERN.search(output):\n            raise RuntimeError(\n                f\"VM license install failed: {output!r}\"\n            )\n\n    def on_block_complete(self):\n        if self._phase in (\"restore\", \"restore-confirmed\"):\n            return\n        if self._phase == \"wait-prompt\":\n            if self._wait_for_prompt:\n                self._wait_for_prompt = False\n                return\n            self._phase = \"done\"\n        if self._phase == \"done\":\n            self.commander.feature_complete(self)\n\n    def on_session_loss(self, attempt):\n        if attempt.spec.session_loss == SessionLossAction.CONTINUE:\n            self._phase = \"wait-prompt\"\n            self._wait_for_prompt = True\n        return attempt.spec.session_loss\n\n\nclass WaitForLicenseValidation(Feature):\n    \"\"\"Poll FortiOS until the restored license validates or times out.\"\"\"\n\n    def __init__(self, vm, commander):\n        super().__init__(vm, commander, \"license-validation\")\n        self._enabled = os.path.exists(\"/tftpboot/appliance.lic\")\n        self._logger = commander.logger\n        self._deadline = None\n        self._next_poll = None\n        self._phase = \"idle\"\n        self._status = None\n        self._status_outputs_logged = set()\n        self._standard_output_active = False\n        self._settle_until = 0\n\n    @property\n    def status(self):\n        return self._status\n\n    @property\n    def valid(self):\n        return self._status is not None and self._status.lower() == \"valid\"\n\n    def activate(self):\n        if not self._enabled:\n            self.commander.feature_complete(self)\n            return\n        self._deadline = time.monotonic() + license_status_timeout_seconds()\n        self._phase = \"polling\"\n        self._next_poll = time.monotonic()\n\n    def on_command_executed(self, command, state):\n        output = bytes(command.output)\n        status = self._license_status(output)\n        self._log_status_output(output, status)\n        normalized_status = status.lower() if status else None\n        if (\n            not status\n            or normalized_status in LICENSE_WAIT_STATUSES\n            or (\n                normalized_status == LICENSE_GRACE_PERIOD_STATUS\n                and wait_for_valid_license()\n            )\n        ):\n            previous_status = self._status.lower() if self._status else None\n            self._status = status\n            if normalized_status != previous_status:\n                self._logger.info(\n                    \"License status is %s; continuing validation polls\",\n                    status or \"unavailable\",\n                )\n            if time.monotonic() >= self._deadline:\n                raise RuntimeError(\n                    \"VM license validation timed out with status \"\n                    f\"{status or 'unavailable'}\"\n                )\n            self._next_poll = time.monotonic() + LICENSE_STATUS_POLL_INTERVAL_SECONDS\n            return\n        self._status = status\n        if normalized_status == LICENSE_GRACE_PERIOD_STATUS:\n            self._logger.info(\n                \"Accepting license status %s without waiting for Valid\",\n                status,\n            )\n            self._finish_validation()\n            return\n        if status.lower() != \"valid\":\n            raise RuntimeError(\n                f\"VM license validation failed: status {status}\"\n            )\n        self._logger.info(f\"License status changed to {status}\")\n        self._finish_validation()\n\n    def _finish_validation(self):\n        self._phase = \"done\"\n        self._settle_until = time.monotonic() + LICENSE_SETTLE_SECONDS\n\n    @staticmethod\n    def _license_status(output):\n        match = re.search(rb\"(?mi)^License Status:\\s*(.+?)\\s*\\r?$\", output)\n        if not match:\n            match = re.search(rb\"(?mi)^License:\\s*(.+?)\\s*\\r?$\", output)\n        return match.group(1).decode(errors=\"replace\").strip() if match else None\n\n    def _log_status_output(self, output, status):\n        if get_env(\n            LOG_LICENSE_STATUS_OUTPUT_ENV, \"false\"\n        ).strip().lower() != \"true\":\n            return\n        normalized_status = status.lower() if status else None\n        if normalized_status in self._status_outputs_logged:\n            return\n        self._status_outputs_logged.add(normalized_status)\n        self._logger.info(\n            \"Captured get system status output for license status %s:\\n%s\",\n            status or \"unavailable\",\n            output.decode(errors=\"replace\").rstrip(),\n        )\n\n    def on_block_complete(self):\n        if self._phase != \"done\":\n            return\n        if time.monotonic() < self._settle_until:\n            return\n        self.commander.feature_complete(self)\n\n    def tick(self):\n        now = time.monotonic()\n        if self._phase == \"done\":\n            if now >= self._settle_until:\n                self.commander.feature_complete(self)\n            return\n        if self._phase != \"polling\" or self._next_poll is None:\n            return\n        if now >= self._deadline:\n            raise RuntimeError(\n                \"VM license validation timed out with status \"\n                f\"{self._status or 'unavailable'}\"\n            )\n        if now >= self._next_poll and not self.commander.busy:\n            self._next_poll = None\n            if self._standard_output_active:\n                self._submit_status_poll()\n            else:\n                self._standard_output_active = True\n                self.commander.with_standard_output(self, self._submit_status_poll)\n\n    def _submit_status_poll(self):\n        self.commander.submit_block(self, CommandSequence(\"license-validation\", [\n            CommandSpec(\"get system status\", capture_output=True, suppress_output=True),\n        ]))",
        "lineStart": 1,
        "lineEnd": 268,
        "totalLines": 268,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716551291,
      "end": 1793716551295
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/credentials.py"
}

Output

<path>/source/head/fortinet/common/features/credentials.py</path>
<type>file</type>
<content>
1: """Administrator bootstrap feature."""
2: 
3: from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction
4: from ..common import FOSCliState
5: 
6: from .base import StaticFeature
7: 
8: 
9: class CredentialsFeature(StaticFeature):
10:     """Configure the administrator, then log out and authenticate again."""
11: 
12:     def __init__(self, vm, commander):
13:         self._activate_after_admin_commit = False
14:         self._desired_credentials_activated = False
15:         self._password_change_committed = False
16:         credentials = vm.desired_credentials
17:         admin_children = ["set accprofile super_admin"]
18:         if credentials.password:
19:             admin_children.append(CommandSpec(
20:                 f"set password {credentials.password}",
21:                 session_loss=SessionLossAction.CONTINUE,
22:                 capture_output=True,
23:                 fail_on_error=True,
24:             ))
25:         elif credentials.username == "admin":
26:             admin_children.append(CommandSpec(
27:                 "unset password", session_loss=SessionLossAction.CONTINUE,
28:                 capture_output=True,
29:                 fail_on_error=True,
30:             ))
31:         super().__init__(vm, commander, "admin", [
32:             ConfigBlock("system password-policy", ["set status disable"]),
33:             ConfigBlock("system admin", [EditBlock(credentials.username, admin_children)]),
34:             CommandSequence("admin-relogin", [CommandSpec(
35:                 "exit",
36:                 session_loss=SessionLossAction.CONTINUE,
37:                 capture_output=True,
38:                 fail_on_error=True,
39:                 # A successful logout takes the session-loss path. Returning
40:                 # straight to a CLI prompt must not count as verification.
41:                 expected_completion_state=FOSCliState.PROVIDE_USERNAME,
42:             )]),
43:         ], on_complete=lambda: self._activate_desired_credentials())
44: 
45:     def on_command_dispatched(self, attempt):
46:         if attempt.spec.line == "exit":
47:             self._activate_desired_credentials()
48:         super().on_command_dispatched(attempt)
49: 
50:     def on_session_loss(self, attempt):
51:         if attempt.spec.line == "exit":
52:             # The commander resumes this block only at the authenticated CLI
53:             # prompt. Clear the logout command so it cannot be replayed.
54:             return SessionLossAction.CONTINUE
55:         if self._is_password_command(attempt.spec.line):
56:             self._activate_desired_credentials()
57:             self._activate_after_admin_commit = False
58:             return SessionLossAction.CONTINUE
59:         if self._activate_after_admin_commit and attempt.spec.line == "next":
60:             # Some releases log out during the commit instead of returning
61:             # its CLI prompt. Authenticate with the committed password.
62:             self._activate_desired_credentials()
63:             self._activate_after_admin_commit = False
64:             self._password_change_committed = True
65:             return SessionLossAction.CONTINUE
66:         if self._password_change_committed:
67:             # FortiOS may log out as the admin edit closes. The password
68:             # command and `next` have already committed the new credentials,
69:             # so replaying this block would use the previous password again.
70:             return SessionLossAction.CONTINUE
71:         return super().on_session_loss(attempt)
72: 
73:     def on_command_executed(self, command, state):
74:         line = command.spec.line
75:         if self._is_password_command(line):
76:             self._activate_after_admin_commit = True
77:         elif self._activate_after_admin_commit and line == "next":
78:             self._activate_desired_credentials()
79:             self._activate_after_admin_commit = False
80:             self._password_change_committed = True
81: 
82:     @staticmethod
83:     def _is_password_command(line):
84:         return line.startswith("set password ") or line == "unset password"
85: 
86:     def _activate_desired_credentials(self):
87:         if self._desired_credentials_activated:
88:             return
89:         self.vm.activate_desired_credentials()
90:         self._desired_credentials_activated = True

(End of file - total 90 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d67eb8001WuHrCSa3NA0L0n",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d672ec0016X1lLBjAUdzQBg",
  "callID": "call_ac355b5a6493417aa1d7b3b5",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/credentials.py"
    },
    "output": "<path>/source/head/fortinet/common/features/credentials.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Administrator bootstrap feature.\"\"\"\n2: \n3: from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n4: from ..common import FOSCliState\n5: \n6: from .base import StaticFeature\n7: \n8: \n9: class CredentialsFeature(StaticFeature):\n10:     \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n11: \n12:     def __init__(self, vm, commander):\n13:         self._activate_after_admin_commit = False\n14:         self._desired_credentials_activated = False\n15:         self._password_change_committed = False\n16:         credentials = vm.desired_credentials\n17:         admin_children = [\"set accprofile super_admin\"]\n18:         if credentials.password:\n19:             admin_children.append(CommandSpec(\n20:                 f\"set password {credentials.password}\",\n21:                 session_loss=SessionLossAction.CONTINUE,\n22:                 capture_output=True,\n23:                 fail_on_error=True,\n24:             ))\n25:         elif credentials.username == \"admin\":\n26:             admin_children.append(CommandSpec(\n27:                 \"unset password\", session_loss=SessionLossAction.CONTINUE,\n28:                 capture_output=True,\n29:                 fail_on_error=True,\n30:             ))\n31:         super().__init__(vm, commander, \"admin\", [\n32:             ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n33:             ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n34:             CommandSequence(\"admin-relogin\", [CommandSpec(\n35:                 \"exit\",\n36:                 session_loss=SessionLossAction.CONTINUE,\n37:                 capture_output=True,\n38:                 fail_on_error=True,\n39:                 # A successful logout takes the session-loss path. Returning\n40:                 # straight to a CLI prompt must not count as verification.\n41:                 expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n42:             )]),\n43:         ], on_complete=lambda: self._activate_desired_credentials())\n44: \n45:     def on_command_dispatched(self, attempt):\n46:         if attempt.spec.line == \"exit\":\n47:             self._activate_desired_credentials()\n48:         super().on_command_dispatched(attempt)\n49: \n50:     def on_session_loss(self, attempt):\n51:         if attempt.spec.line == \"exit\":\n52:             # The commander resumes this block only at the authenticated CLI\n53:             # prompt. Clear the logout command so it cannot be replayed.\n54:             return SessionLossAction.CONTINUE\n55:         if self._is_password_command(attempt.spec.line):\n56:             self._activate_desired_credentials()\n57:             self._activate_after_admin_commit = False\n58:             return SessionLossAction.CONTINUE\n59:         if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n60:             # Some releases log out during the commit instead of returning\n61:             # its CLI prompt. Authenticate with the committed password.\n62:             self._activate_desired_credentials()\n63:             self._activate_after_admin_commit = False\n64:             self._password_change_committed = True\n65:             return SessionLossAction.CONTINUE\n66:         if self._password_change_committed:\n67:             # FortiOS may log out as the admin edit closes. The password\n68:             # command and `next` have already committed the new credentials,\n69:             # so replaying this block would use the previous password again.\n70:             return SessionLossAction.CONTINUE\n71:         return super().on_session_loss(attempt)\n72: \n73:     def on_command_executed(self, command, state):\n74:         line = command.spec.line\n75:         if self._is_password_command(line):\n76:             self._activate_after_admin_commit = True\n77:         elif self._activate_after_admin_commit and line == \"next\":\n78:             self._activate_desired_credentials()\n79:             self._activate_after_admin_commit = False\n80:             self._password_change_committed = True\n81: \n82:     @staticmethod\n83:     def _is_password_command(line):\n84:         return line.startswith(\"set password \") or line == \"unset password\"\n85: \n86:     def _activate_desired_credentials(self):\n87:         if self._desired_credentials_activated:\n88:             return\n89:         self.vm.activate_desired_credentials()\n90:         self._desired_credentials_activated = True\n\n(End of file - total 90 lines)\n</content>",
    "title": "source/head/fortinet/common/features/credentials.py",
    "metadata": {
      "preview": "\"\"\"Administrator bootstrap feature.\"\"\"\n\nfrom ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\nfrom ..common import FOSCliState\n\nfrom .base import StaticFeature\n\n\nclass CredentialsFeature(StaticFeature):\n    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n\n    def __init__(self, vm, commander):\n        self._activate_after_admin_commit = False\n        self._desired_credentials_activated = False\n        self._password_change_committed = False\n        credentials = vm.desired_credentials\n        admin_children = [\"set accprofile super_admin\"]\n        if credentials.password:\n            admin_children.append(CommandSpec(\n                f\"set password {credentials.password}\",",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/credentials.py",
        "text": "\"\"\"Administrator bootstrap feature.\"\"\"\n\nfrom ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\nfrom ..common import FOSCliState\n\nfrom .base import StaticFeature\n\n\nclass CredentialsFeature(StaticFeature):\n    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n\n    def __init__(self, vm, commander):\n        self._activate_after_admin_commit = False\n        self._desired_credentials_activated = False\n        self._password_change_committed = False\n        credentials = vm.desired_credentials\n        admin_children = [\"set accprofile super_admin\"]\n        if credentials.password:\n            admin_children.append(CommandSpec(\n                f\"set password {credentials.password}\",\n                session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n            ))\n        elif credentials.username == \"admin\":\n            admin_children.append(CommandSpec(\n                \"unset password\", session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n            ))\n        super().__init__(vm, commander, \"admin\", [\n            ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n            ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n            CommandSequence(\"admin-relogin\", [CommandSpec(\n                \"exit\",\n                session_loss=SessionLossAction.CONTINUE,\n                capture_output=True,\n                fail_on_error=True,\n                # A successful logout takes the session-loss path. Returning\n                # straight to a CLI prompt must not count as verification.\n                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n            )]),\n        ], on_complete=lambda: self._activate_desired_credentials())\n\n    def on_command_dispatched(self, attempt):\n        if attempt.spec.line == \"exit\":\n            self._activate_desired_credentials()\n        super().on_command_dispatched(attempt)\n\n    def on_session_loss(self, attempt):\n        if attempt.spec.line == \"exit\":\n            # The commander resumes this block only at the authenticated CLI\n            # prompt. Clear the logout command so it cannot be replayed.\n            return SessionLossAction.CONTINUE\n        if self._is_password_command(attempt.spec.line):\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            return SessionLossAction.CONTINUE\n        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n            # Some releases log out during the commit instead of returning\n            # its CLI prompt. Authenticate with the committed password.\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            self._password_change_committed = True\n            return SessionLossAction.CONTINUE\n        if self._password_change_committed:\n            # FortiOS may log out as the admin edit closes. The password\n            # command and `next` have already committed the new credentials,\n            # so replaying this block would use the previous password again.\n            return SessionLossAction.CONTINUE\n        return super().on_session_loss(attempt)\n\n    def on_command_executed(self, command, state):\n        line = command.spec.line\n        if self._is_password_command(line):\n            self._activate_after_admin_commit = True\n        elif self._activate_after_admin_commit and line == \"next\":\n            self._activate_desired_credentials()\n            self._activate_after_admin_commit = False\n            self._password_change_committed = True\n\n    @staticmethod\n    def _is_password_command(line):\n        return line.startswith(\"set password \") or line == \"unset password\"\n\n    def _activate_desired_credentials(self):\n        if self._desired_credentials_activated:\n            return\n        self.vm.activate_desired_credentials()\n        self._desired_credentials_activated = True",
        "lineStart": 1,
        "lineEnd": 90,
        "totalLines": 90,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716551355,
      "end": 1793716551359
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/features/pki.py"
}

Output

<path>/source/head/fortinet/common/features/pki.py</path>
<type>file</type>
<content>
1: """PKI certificate installation feature.
2: 
3: Installs CA certificates (trust), local certificate/key pairs, remote
4: certificates, and certificate revocation lists at bootstrap. Env variables
5: carry paths only; this feature reads the file contents and never logs or
6: stores the certificate, key, or password bytes themselves.
7: 
8: Entries are ``;``-separated and start with a reference-name field followed
9: by ``:`` (``refname:rest``). The refname becomes the FortiOS object name;
10: an empty refname field (``:rest``) implies the object name from the
11: certificate CN.
12: 
13: Env variables:
14: 
15: - ``FTNT_PKI_CA_CERTS``: ``refname:path`` — CAs installed in
16:   ``config vpn certificate ca`` and named by refname or CN.
17: - ``FTNT_PKI_LOCAL_CERTS``: ``refname:key_path:cert_path`` — installed as
18:   local certificate entries named by refname or CN, including the SSL
19:   deep-inspection CA pair (which is just a local cert). Both the private key
20:   and certificate are required.
21: - ``FTNT_PKI_LOCAL_CERT_PASS_FILES``: ``path;path;...`` — positionally paired
22:   with encrypted-key ``refname:key_path:cert_path`` entries; the contents
23:   are typed as ``set password``.
24: - ``FTNT_PKI_REMOTE_CERTS``: ``refname:path`` — remote certificates installed
25:   in ``config vpn certificate remote`` and named by refname or CN.
26: - ``FTNT_PKI_CRLS``: ``refname:path`` — CRLs installed as ``config vpn
27:   certificate crl`` entries with PEM contents when that tree is available,
28:   otherwise imported over TFTP, named by refname or file basename.
29: """
30: 
31: import os
32: import re
33: import shutil
34: import ssl
35: 
36: from ..cli_commands import (
37:     CommandSequence,
38:     CommandSpec,
39:     SetValue,
40: )
41: from ..env import get_env
42: from .base import Feature
43: 
44: 
45: CA_CERTS_ENV = "FOS_PKI_CA_CERTS"
46: LOCAL_CERTS_ENV = "FOS_PKI_LOCAL_CERTS"
47: LOCAL_CERT_PASS_FILES_ENV = "FOS_PKI_LOCAL_CERT_PASS_FILES"
48: REMOTE_CERTS_ENV = "FOS_PKI_REMOTE_CERTS"
49: CRLS_ENV = "FOS_PKI_CRLS"
50: 
51: # The config tree moved back and forth between these names across releases.
52: VPN_CERTIFICATE_CRL_SCOPE = "vpn certificate crl"
53: TFTP_PKI_DIRECTORY = "/tftpboot/pki"
54: COMMAND_FAILURE_PATTERN = re.compile(
55:     rb"(?mi)Unknown action|command (?:parse )?error|Command fail"
56: )
57: 
58: 
59: def _split_entries(variable, value):
60:     """Split ``value`` on ``;`` and strip whitespace, dropping empty entries."""
61:     if value is None:
62:         return []
63:     return [entry for raw in value.split(";") if (entry := raw.strip())]
64: 
65: 
66: def _require_path(variable, path):
67:     if not os.path.exists(path):
68:         raise ValueError(f"{variable}: path does not exist: {path}")
69: 
70: 
71: def _split_refname(entry, variable):
72:     """Split the leading refname field from an entry.
73: 
74:     Every entry is ``refname:rest``; an empty refname field (``:rest``)
75:     means the object name is implied by the certificate CN.
76:     Returns ``(refname_or_None, rest)``.
77:     """
78:     refname, separator, rest = entry.partition(":")
79:     if not separator:
80:         raise ValueError(
81:             f"{variable}: entry '{entry}' must start with a refname field "
82:             "followed by ':'; use ':" + entry + "' to imply the "
83:             "certificate CN"
84:         )
85:     if not rest:
86:         raise ValueError(
87:             f"{variable}: entry '{entry}' must carry a path after the refname"
88:         )
89:     return refname or None, rest
90: 
91: 
92: def parse_ca_certs(value, variable=CA_CERTS_ENV):
93:     """Return ``(refname_or_None, path)`` pairs from ``value``."""
94:     parsed = []
95:     for refname, path in (
96:         _split_refname(entry, variable)
97:         for entry in _split_entries(variable, value)
98:     ):
99:         _require_path(variable, path)
100:         parsed.append((refname, path))
101:     return parsed
102: 
103: 
104: def parse_local_certs(value, variable=LOCAL_CERTS_ENV):
105:     """Return ``(refname_or_None, key_path, cert_path)`` triples.
106: 
107:     Entries are ``refname:key_path:cert_path``. The refname field is always
108:     present; ``:key_path:cert_path`` implies the certificate CN as the object
109:     name. Local certificates require their corresponding private key.
110:     """
111:     parsed = []
112:     for entry in _split_entries(variable, value):
113:         refname, rest = _split_refname(entry, variable)
114:         key_path, separator, cert_path = rest.partition(":")
115:         if not separator:
116:             raise ValueError(
117:                 f"{variable}: entry '{entry}' must include private key and "
118:                 "certificate paths as 'refname:key_path:cert_path'; use "
119:                 "':key_path:cert_path' to imply the certificate CN"
120:             )
121:         _require_path(variable, key_path)
122:         _require_path(variable, cert_path)
123:         parsed.append((refname, key_path, cert_path))
124:     return parsed
125: 
126: 
127: def parse_pass_files(value, variable=LOCAL_CERT_PASS_FILES_ENV):
128:     entries = _split_entries(variable, value)
129:     for entry in entries:
130:         _require_path(variable, entry)
131:     return entries
132: 
133: 
134: def parse_remote_certs(value, variable=REMOTE_CERTS_ENV):
135:     """Return ``(refname_or_None, path)`` pairs from ``value``."""
136:     parsed = []
137:     for refname, path in (
138:         _split_refname(entry, variable)
139:         for entry in _split_entries(variable, value)
140:     ):
141:         _require_path(variable, path)
142:         parsed.append((refname, path))
143:     return parsed
144: 
145: 
146: def parse_crls(value, variable=CRLS_ENV):
147:     """Return ``(refname_or_None, path)`` pairs from ``value``."""
148:     parsed = []
149:     for refname, path in (
150:         _split_refname(entry, variable)
151:         for entry in _split_entries(variable, value)
152:     ):
153:         _require_path(variable, path)
154:         parsed.append((refname, path))
155:     return parsed
156: 
157: 
158: def read_certificate_cn(path):
159:     """Read the subject CN from a PEM certificate file.
160: 
161:     Uses ``ssl._ssl._test_decode_cert``; a minimal DER header scan is the
162:     fallback for builds where the private API is unavailable. Raises
163:     ``ValueError`` naming the file when the CN cannot be determined.
164:     """
165:     try:
166:         if hasattr(ssl._ssl, "_test_decode_cert"):
167:             decoded = ssl._ssl._test_decode_cert(path)
168:             for rdn in decoded.get("subject", ()):
169:                 for attribute, value in rdn:
170:                     if attribute == "commonName":
171:                         return value
172:         raise ValueError(f"Could not read certificate CN from {path}")
173:     except ValueError:
174:         raise
175:     except Exception as error:
176:         raise ValueError(f"Could not read certificate CN from {path}: {error}")
177: 
178: 
179: def read_pass_file(path):
180:     with open(path, "r", encoding="utf-8") as password:
181:         contents = password.read().strip()
182:     if not contents:
183:         raise ValueError(f"{LOCAL_CERT_PASS_FILES_ENV}: empty password file: {path}")
184:     return contents
185: 
186: 
187: def read_crl_body(path):
188:     """Return the CRL file contents for ``set crl``.
189: 
190:     FortiOS documents the field as "Certificate Revocation List as a PEM
191:     file": type the full PEM, headers included. Re-encoding the body a
192:     second time is rejected by 7.4+ with return code -542.
193:     """
194:     with open(path, "r", encoding="utf-8") as crl:
195:         return crl.read()
196: 
197: 
198: class InstallPkiCertificates(Feature):
199:     """Install certificates and CRLs provided by the plugin before startup config.
200: 
201:     Must run after the factory baseline capture and before the user startup
202:     config so the config can reference the installed certificate names.
203:     """
204: 
205:     def __init__(self, vm, commander):
206:         super().__init__(vm, commander, "pki-certificates")
207:         self._logger = commander.logger
208:         self._tftp_server_ip = vm.mgmt_gw_ipv4
209:         self._ca_paths = parse_ca_certs(get_env(CA_CERTS_ENV))
210:         self._local_entries = parse_local_certs(get_env(LOCAL_CERTS_ENV))
211:         self._pass_files = parse_pass_files(get_env(LOCAL_CERT_PASS_FILES_ENV))
212:         self._remote_paths = parse_remote_certs(get_env(REMOTE_CERTS_ENV))
213:         self._crl_paths = parse_crls(get_env(CRLS_ENV))
214:         self._paired_locals = self._pair_pass_files()
215:         self._staging_directory = TFTP_PKI_DIRECTORY
216:         self._phase = "idle"
217:         self._crl_config = None
218:         self._indexes = {"ca": 0, "local": 0, "remote": 0, "crl": 0}
219:         self._seen_names = {"ca": set(), "local": set(), "remote": set(), "crl": set()}
220:         self._current_item = None
221:         self._config_failed = False
222:         self._fallback_active = False
223: 
224:     def _pair_pass_files(self):
225:         """Pair pass files positionally with local entries that carry a key."""
226:         if len(self._pass_files) > len(self._local_entries):
227:             raise ValueError(
228:                 f"{LOCAL_CERT_PASS_FILES_ENV} has more entries than "
229:                 f"{LOCAL_CERTS_ENV}; cannot pair passwords"
230:             )
231:         paired = []
232:         for index, (refname, key_path, cert_path) in enumerate(self._local_entries):
233:             pass_file = self._pass_files[index] if index < len(self._pass_files) else None
234:             paired.append((refname, key_path, cert_path, pass_file))
235:         return paired
236: 
237:     def activate(self):
238:         if not self._blocks_ready():
239:             self.commander.feature_complete(self)
240:             return
241:         version = self.vm.fos_version
242:         if version is None:
243:             raise RuntimeError(
244:                 "FortiOS version is unavailable; image-info must run "
245:                 "before pki-certificates"
246:             )
247:         self._crl_config = self._crl_config_from_major(version.major)
248:         self._phase = "start"
249:         self._submit_next()
250: 
251:     def _blocks_ready(self):
252:         return bool(self._ca_paths or self._local_entries or self._remote_paths or self._crl_paths)
253: 
254:     def _local_with_password(self):
255:         return self._paired_locals
256: 
257:     def _submit_next(self):
258:         if self._phase == "start":
259:             self._phase = "ca-certs"
260:         if self._phase == "ca-certs":
261:             if self._submit_next_ca_cert():
262:                 return
263:             self._phase = "local-certs"
264:         if self._phase == "local-certs":
265:             if self._submit_next_local_cert():
266:                 return
267:             self._phase = "remote-certs"
268:         if self._phase == "remote-certs":
269:             if self._submit_next_remote_cert():
270:                 return
271:             self._phase = "crl-config"
272:         if self._phase == "crl-config":
273:             if self._submit_next_crl():
274:                 return
275:         self.commander.feature_complete(self)
276: 
277:     def _next_entry(self, kind, entries):
278:         index = self._indexes[kind]
279:         if index >= len(entries):
280:             return None
281:         self._indexes[kind] += 1
282:         return index, entries[index]
283: 
284:     def _begin_config_item(self, kind, name, path, block):
285:         if name in self._seen_names[kind]:
286:             self._logger.warning(
287:                 "Duplicate %s certificate name '%s'; last entry wins",
288:                 kind.upper() if kind == "ca" else kind,
289:                 name,
290:             )
291:         self._seen_names[kind].add(name)
292:         self._current_item = (kind, name, path)
293:         self._config_failed = False
294:         self._fallback_active = False
295:         self.commander.submit_block(self, block)
296: 
297:     @staticmethod
298:     def _config_item_block(scope, name, children):
299:         # A configuration attempt is deliberately best-effort: the feature
300:         # must be able to inspect the result and fall back to the TFTP import
301:         # path when a firmware release does not expose this config tree.  If
302:         # opening commands keep ``fail_on_error`` enabled, the commander raises
303:         # before ``on_command_executed`` can select that fallback. A return-code
304:         # failure from `next` or `end` is always fatal to the feature: the
305:         # commander checks scope commits even when fail_on_error is disabled.
306:         def config_command(line):
307:             return CommandSpec(line, capture_output=True, fail_on_error=False)
308: 
309:         return CommandSequence(f"{scope}-{name}", [
310:             config_command(f"config {scope}"),
311:             config_command(f'edit "{name}"'),
312:             *children,
313:             config_command("next"),
314:             config_command("end"),
315:         ])
316: 
317:     def _submit_next_ca_cert(self):
318:         item = self._next_entry("ca", self._ca_paths)
319:         if item is None:
320:             return False
321:         _index, (refname, path) = item
322:         name = refname or read_certificate_cn(path)
323:         with open(path, "r", encoding="utf-8") as certificate:
324:             value = SetValue(
325:                 "ca", certificate.read(),
326:                 fail_on_error=False,
327:                 validate_prompt=False,
328:             )
329:         self._begin_config_item(
330:             "ca", name, path,
331:             self._config_item_block("vpn certificate ca", name, [value]),
332:         )
333:         return True
334: 
335:     def _submit_next_remote_cert(self):
336:         item = self._next_entry("remote", self._remote_paths)
337:         if item is None:
338:             return False
339:         _index, (refname, path) = item
340:         name = refname or read_certificate_cn(path)
341:         with open(path, "r", encoding="utf-8") as certificate:
342:             value = SetValue(
343:                 "remote", certificate.read(),
344:                 fail_on_error=False,
345:                 validate_prompt=False,
346:             )
347:         self._begin_config_item(
348:             "remote", name, path,
349:             self._config_item_block("vpn certificate remote", name, [value]),
350:         )
351:         return True
352: 
353:     def _submit_next_local_cert(self):
354:         item = self._next_entry("local", self._local_with_password())
355:         if item is None:
356:             return False
357:         _index, (refname, key_path, cert_path, pass_file) = item
358:         name = refname or read_certificate_cn(cert_path)
359:         lines = []
360:         if pass_file:
361:             lines.append(CommandSpec(
362:                 f"set password {read_pass_file(pass_file)}",
363:                 capture_output=True,
364:                 fail_on_error=False,
365:             ))
366:         with open(key_path, "r", encoding="utf-8") as key:
367:             lines.append(SetValue(
368:                 "private-key", key.read(),
369:                 fail_on_error=False,
370:                 validate_prompt=False,
371:             ))
372:         with open(cert_path, "r", encoding="utf-8") as cert:
373:             lines.append(SetValue(
374:                 "certificate", cert.read(),
375:                 fail_on_error=False,
376:                 validate_prompt=False,
377:             ))
378:         self._begin_config_item(
379:             "local", name, cert_path,
380:             self._config_item_block("vpn certificate local", name, lines),
381:         )
382:         return True
383: 
384:     def _submit_next_crl(self):
385:         item = self._next_entry("crl", self._crl_paths)
386:         if item is None:
387:             return False
388:         _index, (refname, path) = item
389:         name = refname or self._crl_basename(path)
390:         if self._crl_config is None:
391:             self._current_item = ("crl", name, path)
392:             self._config_failed = True
393:             self._submit_tftp_fallback()
394:             return True
395:         value = SetValue("crl", read_crl_body(path))
396:         self._begin_config_item(
397:             "crl", name, path,
398:             self._config_item_block(VPN_CERTIFICATE_CRL_SCOPE, name, [value]),
399:         )
400:         return True
401: 
402:     def _submit_tftp_fallback(self):
403:         kind, name, path = self._current_item
404:         if kind == "local":
405:             raise RuntimeError(
406:                 f"Failed to install local certificate '{name}' through config; "
407:                 "TFTP cannot import separate private-key and certificate files"
408:             )
409:         filename = name
410:         if not re.fullmatch(r"[A-Za-z0-9_.-]+", filename):
411:             filename = f"pki-{kind}-{self._indexes[kind]:03d}"
412:         os.makedirs(self._staging_directory, exist_ok=True)
413:         shutil.copyfile(path, os.path.join(self._staging_directory, filename))
414:         self._fallback_active = True
415:         self.commander.submit_block(self, CommandSequence(f"{kind}-tftp-fallback", [
416:             CommandSpec(
417:                 f"execute vpn certificate {kind} import tftp "
418:                 f"pki/{filename} {self._tftp_server_ip}",
419:                 capture_output=True,
420:                 # Let on_command_executed produce the object-specific error
421:                 # that identifies both failed installation paths.
422:                 fail_on_error=False,
423:             ),
424:         ]))
425: 
426:     @staticmethod
427:     def _crl_basename(path):
428:         return os.path.splitext(os.path.basename(path))[0]
429: 
430:     def on_command_executed(self, command, state):
431:         if not command.spec.capture_output or not COMMAND_FAILURE_PATTERN.search(
432:             bytes(command.output)
433:         ):
434:             return
435:         if self._fallback_active:
436:             kind, name, _path = self._current_item
437:             raise RuntimeError(
438:                 f"Failed to install {kind} PKI object '{name}' through config "
439:                 "and TFTP"
440:             )
441:         if self._current_item is not None:
442:             self._config_failed = True
443: 
444:     @staticmethod
445:     def _crl_config_from_major(major):
446:         # ``config vpn certificate crl`` exists from 7.0; earlier releases
447:         # expose no CRL CLI at all.
448:         return VPN_CERTIFICATE_CRL_SCOPE if major >= 7 else None
449: 
450:     def on_block_complete(self):
451:         if self._fallback_active:
452:             kind, name, _path = self._current_item
453:             self._logger.warning(
454:                 "Installed %s PKI object '%s' through TFTP after config installation failed",
455:                 kind,
456:                 name,
457:             )
458:             self._fallback_active = False
459:             self._config_failed = False
460:             self._current_item = None
461:             self._submit_next()
462:             return
463:         if self._config_failed:
464:             self._submit_tftp_fallback()
465:             return
466:         self._current_item = None
467:         self._submit_next()
468: 
469:     @property
470:     def completion_message(self):
471:         return None

(End of file - total 471 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d67ee6001jXvsaPWQx97poV",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d672ec0016X1lLBjAUdzQBg",
  "callID": "call_b08031d5d2734a52b1da1564",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/features/pki.py"
    },
    "output": "<path>/source/head/fortinet/common/features/pki.py</path>\n<type>file</type>\n<content>\n1: \"\"\"PKI certificate installation feature.\n2: \n3: Installs CA certificates (trust), local certificate/key pairs, remote\n4: certificates, and certificate revocation lists at bootstrap. Env variables\n5: carry paths only; this feature reads the file contents and never logs or\n6: stores the certificate, key, or password bytes themselves.\n7: \n8: Entries are ``;``-separated and start with a reference-name field followed\n9: by ``:`` (``refname:rest``). The refname becomes the FortiOS object name;\n10: an empty refname field (``:rest``) implies the object name from the\n11: certificate CN.\n12: \n13: Env variables:\n14: \n15: - ``FTNT_PKI_CA_CERTS``: ``refname:path`` — CAs installed in\n16:   ``config vpn certificate ca`` and named by refname or CN.\n17: - ``FTNT_PKI_LOCAL_CERTS``: ``refname:key_path:cert_path`` — installed as\n18:   local certificate entries named by refname or CN, including the SSL\n19:   deep-inspection CA pair (which is just a local cert). Both the private key\n20:   and certificate are required.\n21: - ``FTNT_PKI_LOCAL_CERT_PASS_FILES``: ``path;path;...`` — positionally paired\n22:   with encrypted-key ``refname:key_path:cert_path`` entries; the contents\n23:   are typed as ``set password``.\n24: - ``FTNT_PKI_REMOTE_CERTS``: ``refname:path`` — remote certificates installed\n25:   in ``config vpn certificate remote`` and named by refname or CN.\n26: - ``FTNT_PKI_CRLS``: ``refname:path`` — CRLs installed as ``config vpn\n27:   certificate crl`` entries with PEM contents when that tree is available,\n28:   otherwise imported over TFTP, named by refname or file basename.\n29: \"\"\"\n30: \n31: import os\n32: import re\n33: import shutil\n34: import ssl\n35: \n36: from ..cli_commands import (\n37:     CommandSequence,\n38:     CommandSpec,\n39:     SetValue,\n40: )\n41: from ..env import get_env\n42: from .base import Feature\n43: \n44: \n45: CA_CERTS_ENV = \"FOS_PKI_CA_CERTS\"\n46: LOCAL_CERTS_ENV = \"FOS_PKI_LOCAL_CERTS\"\n47: LOCAL_CERT_PASS_FILES_ENV = \"FOS_PKI_LOCAL_CERT_PASS_FILES\"\n48: REMOTE_CERTS_ENV = \"FOS_PKI_REMOTE_CERTS\"\n49: CRLS_ENV = \"FOS_PKI_CRLS\"\n50: \n51: # The config tree moved back and forth between these names across releases.\n52: VPN_CERTIFICATE_CRL_SCOPE = \"vpn certificate crl\"\n53: TFTP_PKI_DIRECTORY = \"/tftpboot/pki\"\n54: COMMAND_FAILURE_PATTERN = re.compile(\n55:     rb\"(?mi)Unknown action|command (?:parse )?error|Command fail\"\n56: )\n57: \n58: \n59: def _split_entries(variable, value):\n60:     \"\"\"Split ``value`` on ``;`` and strip whitespace, dropping empty entries.\"\"\"\n61:     if value is None:\n62:         return []\n63:     return [entry for raw in value.split(\";\") if (entry := raw.strip())]\n64: \n65: \n66: def _require_path(variable, path):\n67:     if not os.path.exists(path):\n68:         raise ValueError(f\"{variable}: path does not exist: {path}\")\n69: \n70: \n71: def _split_refname(entry, variable):\n72:     \"\"\"Split the leading refname field from an entry.\n73: \n74:     Every entry is ``refname:rest``; an empty refname field (``:rest``)\n75:     means the object name is implied by the certificate CN.\n76:     Returns ``(refname_or_None, rest)``.\n77:     \"\"\"\n78:     refname, separator, rest = entry.partition(\":\")\n79:     if not separator:\n80:         raise ValueError(\n81:             f\"{variable}: entry '{entry}' must start with a refname field \"\n82:             \"followed by ':'; use ':\" + entry + \"' to imply the \"\n83:             \"certificate CN\"\n84:         )\n85:     if not rest:\n86:         raise ValueError(\n87:             f\"{variable}: entry '{entry}' must carry a path after the refname\"\n88:         )\n89:     return refname or None, rest\n90: \n91: \n92: def parse_ca_certs(value, variable=CA_CERTS_ENV):\n93:     \"\"\"Return ``(refname_or_None, path)`` pairs from ``value``.\"\"\"\n94:     parsed = []\n95:     for refname, path in (\n96:         _split_refname(entry, variable)\n97:         for entry in _split_entries(variable, value)\n98:     ):\n99:         _require_path(variable, path)\n100:         parsed.append((refname, path))\n101:     return parsed\n102: \n103: \n104: def parse_local_certs(value, variable=LOCAL_CERTS_ENV):\n105:     \"\"\"Return ``(refname_or_None, key_path, cert_path)`` triples.\n106: \n107:     Entries are ``refname:key_path:cert_path``. The refname field is always\n108:     present; ``:key_path:cert_path`` implies the certificate CN as the object\n109:     name. Local certificates require their corresponding private key.\n110:     \"\"\"\n111:     parsed = []\n112:     for entry in _split_entries(variable, value):\n113:         refname, rest = _split_refname(entry, variable)\n114:         key_path, separator, cert_path = rest.partition(\":\")\n115:         if not separator:\n116:             raise ValueError(\n117:                 f\"{variable}: entry '{entry}' must include private key and \"\n118:                 \"certificate paths as 'refname:key_path:cert_path'; use \"\n119:                 \"':key_path:cert_path' to imply the certificate CN\"\n120:             )\n121:         _require_path(variable, key_path)\n122:         _require_path(variable, cert_path)\n123:         parsed.append((refname, key_path, cert_path))\n124:     return parsed\n125: \n126: \n127: def parse_pass_files(value, variable=LOCAL_CERT_PASS_FILES_ENV):\n128:     entries = _split_entries(variable, value)\n129:     for entry in entries:\n130:         _require_path(variable, entry)\n131:     return entries\n132: \n133: \n134: def parse_remote_certs(value, variable=REMOTE_CERTS_ENV):\n135:     \"\"\"Return ``(refname_or_None, path)`` pairs from ``value``.\"\"\"\n136:     parsed = []\n137:     for refname, path in (\n138:         _split_refname(entry, variable)\n139:         for entry in _split_entries(variable, value)\n140:     ):\n141:         _require_path(variable, path)\n142:         parsed.append((refname, path))\n143:     return parsed\n144: \n145: \n146: def parse_crls(value, variable=CRLS_ENV):\n147:     \"\"\"Return ``(refname_or_None, path)`` pairs from ``value``.\"\"\"\n148:     parsed = []\n149:     for refname, path in (\n150:         _split_refname(entry, variable)\n151:         for entry in _split_entries(variable, value)\n152:     ):\n153:         _require_path(variable, path)\n154:         parsed.append((refname, path))\n155:     return parsed\n156: \n157: \n158: def read_certificate_cn(path):\n159:     \"\"\"Read the subject CN from a PEM certificate file.\n160: \n161:     Uses ``ssl._ssl._test_decode_cert``; a minimal DER header scan is the\n162:     fallback for builds where the private API is unavailable. Raises\n163:     ``ValueError`` naming the file when the CN cannot be determined.\n164:     \"\"\"\n165:     try:\n166:         if hasattr(ssl._ssl, \"_test_decode_cert\"):\n167:             decoded = ssl._ssl._test_decode_cert(path)\n168:             for rdn in decoded.get(\"subject\", ()):\n169:                 for attribute, value in rdn:\n170:                     if attribute == \"commonName\":\n171:                         return value\n172:         raise ValueError(f\"Could not read certificate CN from {path}\")\n173:     except ValueError:\n174:         raise\n175:     except Exception as error:\n176:         raise ValueError(f\"Could not read certificate CN from {path}: {error}\")\n177: \n178: \n179: def read_pass_file(path):\n180:     with open(path, \"r\", encoding=\"utf-8\") as password:\n181:         contents = password.read().strip()\n182:     if not contents:\n183:         raise ValueError(f\"{LOCAL_CERT_PASS_FILES_ENV}: empty password file: {path}\")\n184:     return contents\n185: \n186: \n187: def read_crl_body(path):\n188:     \"\"\"Return the CRL file contents for ``set crl``.\n189: \n190:     FortiOS documents the field as \"Certificate Revocation List as a PEM\n191:     file\": type the full PEM, headers included. Re-encoding the body a\n192:     second time is rejected by 7.4+ with return code -542.\n193:     \"\"\"\n194:     with open(path, \"r\", encoding=\"utf-8\") as crl:\n195:         return crl.read()\n196: \n197: \n198: class InstallPkiCertificates(Feature):\n199:     \"\"\"Install certificates and CRLs provided by the plugin before startup config.\n200: \n201:     Must run after the factory baseline capture and before the user startup\n202:     config so the config can reference the installed certificate names.\n203:     \"\"\"\n204: \n205:     def __init__(self, vm, commander):\n206:         super().__init__(vm, commander, \"pki-certificates\")\n207:         self._logger = commander.logger\n208:         self._tftp_server_ip = vm.mgmt_gw_ipv4\n209:         self._ca_paths = parse_ca_certs(get_env(CA_CERTS_ENV))\n210:         self._local_entries = parse_local_certs(get_env(LOCAL_CERTS_ENV))\n211:         self._pass_files = parse_pass_files(get_env(LOCAL_CERT_PASS_FILES_ENV))\n212:         self._remote_paths = parse_remote_certs(get_env(REMOTE_CERTS_ENV))\n213:         self._crl_paths = parse_crls(get_env(CRLS_ENV))\n214:         self._paired_locals = self._pair_pass_files()\n215:         self._staging_directory = TFTP_PKI_DIRECTORY\n216:         self._phase = \"idle\"\n217:         self._crl_config = None\n218:         self._indexes = {\"ca\": 0, \"local\": 0, \"remote\": 0, \"crl\": 0}\n219:         self._seen_names = {\"ca\": set(), \"local\": set(), \"remote\": set(), \"crl\": set()}\n220:         self._current_item = None\n221:         self._config_failed = False\n222:         self._fallback_active = False\n223: \n224:     def _pair_pass_files(self):\n225:         \"\"\"Pair pass files positionally with local entries that carry a key.\"\"\"\n226:         if len(self._pass_files) > len(self._local_entries):\n227:             raise ValueError(\n228:                 f\"{LOCAL_CERT_PASS_FILES_ENV} has more entries than \"\n229:                 f\"{LOCAL_CERTS_ENV}; cannot pair passwords\"\n230:             )\n231:         paired = []\n232:         for index, (refname, key_path, cert_path) in enumerate(self._local_entries):\n233:             pass_file = self._pass_files[index] if index < len(self._pass_files) else None\n234:             paired.append((refname, key_path, cert_path, pass_file))\n235:         return paired\n236: \n237:     def activate(self):\n238:         if not self._blocks_ready():\n239:             self.commander.feature_complete(self)\n240:             return\n241:         version = self.vm.fos_version\n242:         if version is None:\n243:             raise RuntimeError(\n244:                 \"FortiOS version is unavailable; image-info must run \"\n245:                 \"before pki-certificates\"\n246:             )\n247:         self._crl_config = self._crl_config_from_major(version.major)\n248:         self._phase = \"start\"\n249:         self._submit_next()\n250: \n251:     def _blocks_ready(self):\n252:         return bool(self._ca_paths or self._local_entries or self._remote_paths or self._crl_paths)\n253: \n254:     def _local_with_password(self):\n255:         return self._paired_locals\n256: \n257:     def _submit_next(self):\n258:         if self._phase == \"start\":\n259:             self._phase = \"ca-certs\"\n260:         if self._phase == \"ca-certs\":\n261:             if self._submit_next_ca_cert():\n262:                 return\n263:             self._phase = \"local-certs\"\n264:         if self._phase == \"local-certs\":\n265:             if self._submit_next_local_cert():\n266:                 return\n267:             self._phase = \"remote-certs\"\n268:         if self._phase == \"remote-certs\":\n269:             if self._submit_next_remote_cert():\n270:                 return\n271:             self._phase = \"crl-config\"\n272:         if self._phase == \"crl-config\":\n273:             if self._submit_next_crl():\n274:                 return\n275:         self.commander.feature_complete(self)\n276: \n277:     def _next_entry(self, kind, entries):\n278:         index = self._indexes[kind]\n279:         if index >= len(entries):\n280:             return None\n281:         self._indexes[kind] += 1\n282:         return index, entries[index]\n283: \n284:     def _begin_config_item(self, kind, name, path, block):\n285:         if name in self._seen_names[kind]:\n286:             self._logger.warning(\n287:                 \"Duplicate %s certificate name '%s'; last entry wins\",\n288:                 kind.upper() if kind == \"ca\" else kind,\n289:                 name,\n290:             )\n291:         self._seen_names[kind].add(name)\n292:         self._current_item = (kind, name, path)\n293:         self._config_failed = False\n294:         self._fallback_active = False\n295:         self.commander.submit_block(self, block)\n296: \n297:     @staticmethod\n298:     def _config_item_block(scope, name, children):\n299:         # A configuration attempt is deliberately best-effort: the feature\n300:         # must be able to inspect the result and fall back to the TFTP import\n301:         # path when a firmware release does not expose this config tree.  If\n302:         # opening commands keep ``fail_on_error`` enabled, the commander raises\n303:         # before ``on_command_executed`` can select that fallback. A return-code\n304:         # failure from `next` or `end` is always fatal to the feature: the\n305:         # commander checks scope commits even when fail_on_error is disabled.\n306:         def config_command(line):\n307:             return CommandSpec(line, capture_output=True, fail_on_error=False)\n308: \n309:         return CommandSequence(f\"{scope}-{name}\", [\n310:             config_command(f\"config {scope}\"),\n311:             config_command(f'edit \"{name}\"'),\n312:             *children,\n313:             config_command(\"next\"),\n314:             config_command(\"end\"),\n315:         ])\n316: \n317:     def _submit_next_ca_cert(self):\n318:         item = self._next_entry(\"ca\", self._ca_paths)\n319:         if item is None:\n320:             return False\n321:         _index, (refname, path) = item\n322:         name = refname or read_certificate_cn(path)\n323:         with open(path, \"r\", encoding=\"utf-8\") as certificate:\n324:             value = SetValue(\n325:                 \"ca\", certificate.read(),\n326:                 fail_on_error=False,\n327:                 validate_prompt=False,\n328:             )\n329:         self._begin_config_item(\n330:             \"ca\", name, path,\n331:             self._config_item_block(\"vpn certificate ca\", name, [value]),\n332:         )\n333:         return True\n334: \n335:     def _submit_next_remote_cert(self):\n336:         item = self._next_entry(\"remote\", self._remote_paths)\n337:         if item is None:\n338:             return False\n339:         _index, (refname, path) = item\n340:         name = refname or read_certificate_cn(path)\n341:         with open(path, \"r\", encoding=\"utf-8\") as certificate:\n342:             value = SetValue(\n343:                 \"remote\", certificate.read(),\n344:                 fail_on_error=False,\n345:                 validate_prompt=False,\n346:             )\n347:         self._begin_config_item(\n348:             \"remote\", name, path,\n349:             self._config_item_block(\"vpn certificate remote\", name, [value]),\n350:         )\n351:         return True\n352: \n353:     def _submit_next_local_cert(self):\n354:         item = self._next_entry(\"local\", self._local_with_password())\n355:         if item is None:\n356:             return False\n357:         _index, (refname, key_path, cert_path, pass_file) = item\n358:         name = refname or read_certificate_cn(cert_path)\n359:         lines = []\n360:         if pass_file:\n361:             lines.append(CommandSpec(\n362:                 f\"set password {read_pass_file(pass_file)}\",\n363:                 capture_output=True,\n364:                 fail_on_error=False,\n365:             ))\n366:         with open(key_path, \"r\", encoding=\"utf-8\") as key:\n367:             lines.append(SetValue(\n368:                 \"private-key\", key.read(),\n369:                 fail_on_error=False,\n370:                 validate_prompt=False,\n371:             ))\n372:         with open(cert_path, \"r\", encoding=\"utf-8\") as cert:\n373:             lines.append(SetValue(\n374:                 \"certificate\", cert.read(),\n375:                 fail_on_error=False,\n376:                 validate_prompt=False,\n377:             ))\n378:         self._begin_config_item(\n379:             \"local\", name, cert_path,\n380:             self._config_item_block(\"vpn certificate local\", name, lines),\n381:         )\n382:         return True\n383: \n384:     def _submit_next_crl(self):\n385:         item = self._next_entry(\"crl\", self._crl_paths)\n386:         if item is None:\n387:             return False\n388:         _index, (refname, path) = item\n389:         name = refname or self._crl_basename(path)\n390:         if self._crl_config is None:\n391:             self._current_item = (\"crl\", name, path)\n392:             self._config_failed = True\n393:             self._submit_tftp_fallback()\n394:             return True\n395:         value = SetValue(\"crl\", read_crl_body(path))\n396:         self._begin_config_item(\n397:             \"crl\", name, path,\n398:             self._config_item_block(VPN_CERTIFICATE_CRL_SCOPE, name, [value]),\n399:         )\n400:         return True\n401: \n402:     def _submit_tftp_fallback(self):\n403:         kind, name, path = self._current_item\n404:         if kind == \"local\":\n405:             raise RuntimeError(\n406:                 f\"Failed to install local certificate '{name}' through config; \"\n407:                 \"TFTP cannot import separate private-key and certificate files\"\n408:             )\n409:         filename = name\n410:         if not re.fullmatch(r\"[A-Za-z0-9_.-]+\", filename):\n411:             filename = f\"pki-{kind}-{self._indexes[kind]:03d}\"\n412:         os.makedirs(self._staging_directory, exist_ok=True)\n413:         shutil.copyfile(path, os.path.join(self._staging_directory, filename))\n414:         self._fallback_active = True\n415:         self.commander.submit_block(self, CommandSequence(f\"{kind}-tftp-fallback\", [\n416:             CommandSpec(\n417:                 f\"execute vpn certificate {kind} import tftp \"\n418:                 f\"pki/{filename} {self._tftp_server_ip}\",\n419:                 capture_output=True,\n420:                 # Let on_command_executed produce the object-specific error\n421:                 # that identifies both failed installation paths.\n422:                 fail_on_error=False,\n423:             ),\n424:         ]))\n425: \n426:     @staticmethod\n427:     def _crl_basename(path):\n428:         return os.path.splitext(os.path.basename(path))[0]\n429: \n430:     def on_command_executed(self, command, state):\n431:         if not command.spec.capture_output or not COMMAND_FAILURE_PATTERN.search(\n432:             bytes(command.output)\n433:         ):\n434:             return\n435:         if self._fallback_active:\n436:             kind, name, _path = self._current_item\n437:             raise RuntimeError(\n438:                 f\"Failed to install {kind} PKI object '{name}' through config \"\n439:                 \"and TFTP\"\n440:             )\n441:         if self._current_item is not None:\n442:             self._config_failed = True\n443: \n444:     @staticmethod\n445:     def _crl_config_from_major(major):\n446:         # ``config vpn certificate crl`` exists from 7.0; earlier releases\n447:         # expose no CRL CLI at all.\n448:         return VPN_CERTIFICATE_CRL_SCOPE if major >= 7 else None\n449: \n450:     def on_block_complete(self):\n451:         if self._fallback_active:\n452:             kind, name, _path = self._current_item\n453:             self._logger.warning(\n454:                 \"Installed %s PKI object '%s' through TFTP after config installation failed\",\n455:                 kind,\n456:                 name,\n457:             )\n458:             self._fallback_active = False\n459:             self._config_failed = False\n460:             self._current_item = None\n461:             self._submit_next()\n462:             return\n463:         if self._config_failed:\n464:             self._submit_tftp_fallback()\n465:             return\n466:         self._current_item = None\n467:         self._submit_next()\n468: \n469:     @property\n470:     def completion_message(self):\n471:         return None\n\n(End of file - total 471 lines)\n</content>",
    "title": "source/head/fortinet/common/features/pki.py",
    "metadata": {
      "preview": "\"\"\"PKI certificate installation feature.\n\nInstalls CA certificates (trust), local certificate/key pairs, remote\ncertificates, and certificate revocation lists at bootstrap. Env variables\ncarry paths only; this feature reads the file contents and never logs or\nstores the certificate, key, or password bytes themselves.\n\nEntries are ``;``-separated and start with a reference-name field followed\nby ``:`` (``refname:rest``). The refname becomes the FortiOS object name;\nan empty refname field (``:rest``) implies the object name from the\ncertificate CN.\n\nEnv variables:\n\n- ``FTNT_PKI_CA_CERTS``: ``refname:path`` — CAs installed in\n  ``config vpn certificate ca`` and named by refname or CN.\n- ``FTNT_PKI_LOCAL_CERTS``: ``refname:key_path:cert_path`` — installed as\n  local certificate entries named by refname or CN, including the SSL\n  deep-inspection CA pair (which is just a local cert). Both the private key\n  and certificate are required.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/features/pki.py",
        "text": "\"\"\"PKI certificate installation feature.\n\nInstalls CA certificates (trust), local certificate/key pairs, remote\ncertificates, and certificate revocation lists at bootstrap. Env variables\ncarry paths only; this feature reads the file contents and never logs or\nstores the certificate, key, or password bytes themselves.\n\nEntries are ``;``-separated and start with a reference-name field followed\nby ``:`` (``refname:rest``). The refname becomes the FortiOS object name;\nan empty refname field (``:rest``) implies the object name from the\ncertificate CN.\n\nEnv variables:\n\n- ``FTNT_PKI_CA_CERTS``: ``refname:path`` — CAs installed in\n  ``config vpn certificate ca`` and named by refname or CN.\n- ``FTNT_PKI_LOCAL_CERTS``: ``refname:key_path:cert_path`` — installed as\n  local certificate entries named by refname or CN, including the SSL\n  deep-inspection CA pair (which is just a local cert). Both the private key\n  and certificate are required.\n- ``FTNT_PKI_LOCAL_CERT_PASS_FILES``: ``path;path;...`` — positionally paired\n  with encrypted-key ``refname:key_path:cert_path`` entries; the contents\n  are typed as ``set password``.\n- ``FTNT_PKI_REMOTE_CERTS``: ``refname:path`` — remote certificates installed\n  in ``config vpn certificate remote`` and named by refname or CN.\n- ``FTNT_PKI_CRLS``: ``refname:path`` — CRLs installed as ``config vpn\n  certificate crl`` entries with PEM contents when that tree is available,\n  otherwise imported over TFTP, named by refname or file basename.\n\"\"\"\n\nimport os\nimport re\nimport shutil\nimport ssl\n\nfrom ..cli_commands import (\n    CommandSequence,\n    CommandSpec,\n    SetValue,\n)\nfrom ..env import get_env\nfrom .base import Feature\n\n\nCA_CERTS_ENV = \"FOS_PKI_CA_CERTS\"\nLOCAL_CERTS_ENV = \"FOS_PKI_LOCAL_CERTS\"\nLOCAL_CERT_PASS_FILES_ENV = \"FOS_PKI_LOCAL_CERT_PASS_FILES\"\nREMOTE_CERTS_ENV = \"FOS_PKI_REMOTE_CERTS\"\nCRLS_ENV = \"FOS_PKI_CRLS\"\n\n# The config tree moved back and forth between these names across releases.\nVPN_CERTIFICATE_CRL_SCOPE = \"vpn certificate crl\"\nTFTP_PKI_DIRECTORY = \"/tftpboot/pki\"\nCOMMAND_FAILURE_PATTERN = re.compile(\n    rb\"(?mi)Unknown action|command (?:parse )?error|Command fail\"\n)\n\n\ndef _split_entries(variable, value):\n    \"\"\"Split ``value`` on ``;`` and strip whitespace, dropping empty entries.\"\"\"\n    if value is None:\n        return []\n    return [entry for raw in value.split(\";\") if (entry := raw.strip())]\n\n\ndef _require_path(variable, path):\n    if not os.path.exists(path):\n        raise ValueError(f\"{variable}: path does not exist: {path}\")\n\n\ndef _split_refname(entry, variable):\n    \"\"\"Split the leading refname field from an entry.\n\n    Every entry is ``refname:rest``; an empty refname field (``:rest``)\n    means the object name is implied by the certificate CN.\n    Returns ``(refname_or_None, rest)``.\n    \"\"\"\n    refname, separator, rest = entry.partition(\":\")\n    if not separator:\n        raise ValueError(\n            f\"{variable}: entry '{entry}' must start with a refname field \"\n            \"followed by ':'; use ':\" + entry + \"' to imply the \"\n            \"certificate CN\"\n        )\n    if not rest:\n        raise ValueError(\n            f\"{variable}: entry '{entry}' must carry a path after the refname\"\n        )\n    return refname or None, rest\n\n\ndef parse_ca_certs(value, variable=CA_CERTS_ENV):\n    \"\"\"Return ``(refname_or_None, path)`` pairs from ``value``.\"\"\"\n    parsed = []\n    for refname, path in (\n        _split_refname(entry, variable)\n        for entry in _split_entries(variable, value)\n    ):\n        _require_path(variable, path)\n        parsed.append((refname, path))\n    return parsed\n\n\ndef parse_local_certs(value, variable=LOCAL_CERTS_ENV):\n    \"\"\"Return ``(refname_or_None, key_path, cert_path)`` triples.\n\n    Entries are ``refname:key_path:cert_path``. The refname field is always\n    present; ``:key_path:cert_path`` implies the certificate CN as the object\n    name. Local certificates require their corresponding private key.\n    \"\"\"\n    parsed = []\n    for entry in _split_entries(variable, value):\n        refname, rest = _split_refname(entry, variable)\n        key_path, separator, cert_path = rest.partition(\":\")\n        if not separator:\n            raise ValueError(\n                f\"{variable}: entry '{entry}' must include private key and \"\n                \"certificate paths as 'refname:key_path:cert_path'; use \"\n                \"':key_path:cert_path' to imply the certificate CN\"\n            )\n        _require_path(variable, key_path)\n        _require_path(variable, cert_path)\n        parsed.append((refname, key_path, cert_path))\n    return parsed\n\n\ndef parse_pass_files(value, variable=LOCAL_CERT_PASS_FILES_ENV):\n    entries = _split_entries(variable, value)\n    for entry in entries:\n        _require_path(variable, entry)\n    return entries\n\n\ndef parse_remote_certs(value, variable=REMOTE_CERTS_ENV):\n    \"\"\"Return ``(refname_or_None, path)`` pairs from ``value``.\"\"\"\n    parsed = []\n    for refname, path in (\n        _split_refname(entry, variable)\n        for entry in _split_entries(variable, value)\n    ):\n        _require_path(variable, path)\n        parsed.append((refname, path))\n    return parsed\n\n\ndef parse_crls(value, variable=CRLS_ENV):\n    \"\"\"Return ``(refname_or_None, path)`` pairs from ``value``.\"\"\"\n    parsed = []\n    for refname, path in (\n        _split_refname(entry, variable)\n        for entry in _split_entries(variable, value)\n    ):\n        _require_path(variable, path)\n        parsed.append((refname, path))\n    return parsed\n\n\ndef read_certificate_cn(path):\n    \"\"\"Read the subject CN from a PEM certificate file.\n\n    Uses ``ssl._ssl._test_decode_cert``; a minimal DER header scan is the\n    fallback for builds where the private API is unavailable. Raises\n    ``ValueError`` naming the file when the CN cannot be determined.\n    \"\"\"\n    try:\n        if hasattr(ssl._ssl, \"_test_decode_cert\"):\n            decoded = ssl._ssl._test_decode_cert(path)\n            for rdn in decoded.get(\"subject\", ()):\n                for attribute, value in rdn:\n                    if attribute == \"commonName\":\n                        return value\n        raise ValueError(f\"Could not read certificate CN from {path}\")\n    except ValueError:\n        raise\n    except Exception as error:\n        raise ValueError(f\"Could not read certificate CN from {path}: {error}\")\n\n\ndef read_pass_file(path):\n    with open(path, \"r\", encoding=\"utf-8\") as password:\n        contents = password.read().strip()\n    if not contents:\n        raise ValueError(f\"{LOCAL_CERT_PASS_FILES_ENV}: empty password file: {path}\")\n    return contents\n\n\ndef read_crl_body(path):\n    \"\"\"Return the CRL file contents for ``set crl``.\n\n    FortiOS documents the field as \"Certificate Revocation List as a PEM\n    file\": type the full PEM, headers included. Re-encoding the body a\n    second time is rejected by 7.4+ with return code -542.\n    \"\"\"\n    with open(path, \"r\", encoding=\"utf-8\") as crl:\n        return crl.read()\n\n\nclass InstallPkiCertificates(Feature):\n    \"\"\"Install certificates and CRLs provided by the plugin before startup config.\n\n    Must run after the factory baseline capture and before the user startup\n    config so the config can reference the installed certificate names.\n    \"\"\"\n\n    def __init__(self, vm, commander):\n        super().__init__(vm, commander, \"pki-certificates\")\n        self._logger = commander.logger\n        self._tftp_server_ip = vm.mgmt_gw_ipv4\n        self._ca_paths = parse_ca_certs(get_env(CA_CERTS_ENV))\n        self._local_entries = parse_local_certs(get_env(LOCAL_CERTS_ENV))\n        self._pass_files = parse_pass_files(get_env(LOCAL_CERT_PASS_FILES_ENV))\n        self._remote_paths = parse_remote_certs(get_env(REMOTE_CERTS_ENV))\n        self._crl_paths = parse_crls(get_env(CRLS_ENV))\n        self._paired_locals = self._pair_pass_files()\n        self._staging_directory = TFTP_PKI_DIRECTORY\n        self._phase = \"idle\"\n        self._crl_config = None\n        self._indexes = {\"ca\": 0, \"local\": 0, \"remote\": 0, \"crl\": 0}\n        self._seen_names = {\"ca\": set(), \"local\": set(), \"remote\": set(), \"crl\": set()}\n        self._current_item = None\n        self._config_failed = False\n        self._fallback_active = False\n\n    def _pair_pass_files(self):\n        \"\"\"Pair pass files positionally with local entries that carry a key.\"\"\"\n        if len(self._pass_files) > len(self._local_entries):\n            raise ValueError(\n                f\"{LOCAL_CERT_PASS_FILES_ENV} has more entries than \"\n                f\"{LOCAL_CERTS_ENV}; cannot pair passwords\"\n            )\n        paired = []\n        for index, (refname, key_path, cert_path) in enumerate(self._local_entries):\n            pass_file = self._pass_files[index] if index < len(self._pass_files) else None\n            paired.append((refname, key_path, cert_path, pass_file))\n        return paired\n\n    def activate(self):\n        if not self._blocks_ready():\n            self.commander.feature_complete(self)\n            return\n        version = self.vm.fos_version\n        if version is None:\n            raise RuntimeError(\n                \"FortiOS version is unavailable; image-info must run \"\n                \"before pki-certificates\"\n            )\n        self._crl_config = self._crl_config_from_major(version.major)\n        self._phase = \"start\"\n        self._submit_next()\n\n    def _blocks_ready(self):\n        return bool(self._ca_paths or self._local_entries or self._remote_paths or self._crl_paths)\n\n    def _local_with_password(self):\n        return self._paired_locals\n\n    def _submit_next(self):\n        if self._phase == \"start\":\n            self._phase = \"ca-certs\"\n        if self._phase == \"ca-certs\":\n            if self._submit_next_ca_cert():\n                return\n            self._phase = \"local-certs\"\n        if self._phase == \"local-certs\":\n            if self._submit_next_local_cert():\n                return\n            self._phase = \"remote-certs\"\n        if self._phase == \"remote-certs\":\n            if self._submit_next_remote_cert():\n                return\n            self._phase = \"crl-config\"\n        if self._phase == \"crl-config\":\n            if self._submit_next_crl():\n                return\n        self.commander.feature_complete(self)\n\n    def _next_entry(self, kind, entries):\n        index = self._indexes[kind]\n        if index >= len(entries):\n            return None\n        self._indexes[kind] += 1\n        return index, entries[index]\n\n    def _begin_config_item(self, kind, name, path, block):\n        if name in self._seen_names[kind]:\n            self._logger.warning(\n                \"Duplicate %s certificate name '%s'; last entry wins\",\n                kind.upper() if kind == \"ca\" else kind,\n                name,\n            )\n        self._seen_names[kind].add(name)\n        self._current_item = (kind, name, path)\n        self._config_failed = False\n        self._fallback_active = False\n        self.commander.submit_block(self, block)\n\n    @staticmethod\n    def _config_item_block(scope, name, children):\n        # A configuration attempt is deliberately best-effort: the feature\n        # must be able to inspect the result and fall back to the TFTP import\n        # path when a firmware release does not expose this config tree.  If\n        # opening commands keep ``fail_on_error`` enabled, the commander raises\n        # before ``on_command_executed`` can select that fallback. A return-code\n        # failure from `next` or `end` is always fatal to the feature: the\n        # commander checks scope commits even when fail_on_error is disabled.\n        def config_command(line):\n            return CommandSpec(line, capture_output=True, fail_on_error=False)\n\n        return CommandSequence(f\"{scope}-{name}\", [\n            config_command(f\"config {scope}\"),\n            config_command(f'edit \"{name}\"'),\n            *children,\n            config_command(\"next\"),\n            config_command(\"end\"),\n        ])\n\n    def _submit_next_ca_cert(self):\n        item = self._next_entry(\"ca\", self._ca_paths)\n        if item is None:\n            return False\n        _index, (refname, path) = item\n        name = refname or read_certificate_cn(path)\n        with open(path, \"r\", encoding=\"utf-8\") as certificate:\n            value = SetValue(\n                \"ca\", certificate.read(),\n                fail_on_error=False,\n                validate_prompt=False,\n            )\n        self._begin_config_item(\n            \"ca\", name, path,\n            self._config_item_block(\"vpn certificate ca\", name, [value]),\n        )\n        return True\n\n    def _submit_next_remote_cert(self):\n        item = self._next_entry(\"remote\", self._remote_paths)\n        if item is None:\n            return False\n        _index, (refname, path) = item\n        name = refname or read_certificate_cn(path)\n        with open(path, \"r\", encoding=\"utf-8\") as certificate:\n            value = SetValue(\n                \"remote\", certificate.read(),\n                fail_on_error=False,\n                validate_prompt=False,\n            )\n        self._begin_config_item(\n            \"remote\", name, path,\n            self._config_item_block(\"vpn certificate remote\", name, [value]),\n        )\n        return True\n\n    def _submit_next_local_cert(self):\n        item = self._next_entry(\"local\", self._local_with_password())\n        if item is None:\n            return False\n        _index, (refname, key_path, cert_path, pass_file) = item\n        name = refname or read_certificate_cn(cert_path)\n        lines = []\n        if pass_file:\n            lines.append(CommandSpec(\n                f\"set password {read_pass_file(pass_file)}\",\n                capture_output=True,\n                fail_on_error=False,\n            ))\n        with open(key_path, \"r\", encoding=\"utf-8\") as key:\n            lines.append(SetValue(\n                \"private-key\", key.read(),\n                fail_on_error=False,\n                validate_prompt=False,\n            ))\n        with open(cert_path, \"r\", encoding=\"utf-8\") as cert:\n            lines.append(SetValue(\n                \"certificate\", cert.read(),\n                fail_on_error=False,\n                validate_prompt=False,\n            ))\n        self._begin_config_item(\n            \"local\", name, cert_path,\n            self._config_item_block(\"vpn certificate local\", name, lines),\n        )\n        return True\n\n    def _submit_next_crl(self):\n        item = self._next_entry(\"crl\", self._crl_paths)\n        if item is None:\n            return False\n        _index, (refname, path) = item\n        name = refname or self._crl_basename(path)\n        if self._crl_config is None:\n            self._current_item = (\"crl\", name, path)\n            self._config_failed = True\n            self._submit_tftp_fallback()\n            return True\n        value = SetValue(\"crl\", read_crl_body(path))\n        self._begin_config_item(\n            \"crl\", name, path,\n            self._config_item_block(VPN_CERTIFICATE_CRL_SCOPE, name, [value]),\n        )\n        return True\n\n    def _submit_tftp_fallback(self):\n        kind, name, path = self._current_item\n        if kind == \"local\":\n            raise RuntimeError(\n                f\"Failed to install local certificate '{name}' through config; \"\n                \"TFTP cannot import separate private-key and certificate files\"\n            )\n        filename = name\n        if not re.fullmatch(r\"[A-Za-z0-9_.-]+\", filename):\n            filename = f\"pki-{kind}-{self._indexes[kind]:03d}\"\n        os.makedirs(self._staging_directory, exist_ok=True)\n        shutil.copyfile(path, os.path.join(self._staging_directory, filename))\n        self._fallback_active = True\n        self.commander.submit_block(self, CommandSequence(f\"{kind}-tftp-fallback\", [\n            CommandSpec(\n                f\"execute vpn certificate {kind} import tftp \"\n                f\"pki/{filename} {self._tftp_server_ip}\",\n                capture_output=True,\n                # Let on_command_executed produce the object-specific error\n                # that identifies both failed installation paths.\n                fail_on_error=False,\n            ),\n        ]))\n\n    @staticmethod\n    def _crl_basename(path):\n        return os.path.splitext(os.path.basename(path))[0]\n\n    def on_command_executed(self, command, state):\n        if not command.spec.capture_output or not COMMAND_FAILURE_PATTERN.search(\n            bytes(command.output)\n        ):\n            return\n        if self._fallback_active:\n            kind, name, _path = self._current_item\n            raise RuntimeError(\n                f\"Failed to install {kind} PKI object '{name}' through config \"\n                \"and TFTP\"\n            )\n        if self._current_item is not None:\n            self._config_failed = True\n\n    @staticmethod\n    def _crl_config_from_major(major):\n        # ``config vpn certificate crl`` exists from 7.0; earlier releases\n        # expose no CRL CLI at all.\n        return VPN_CERTIFICATE_CRL_SCOPE if major >= 7 else None\n\n    def on_block_complete(self):\n        if self._fallback_active:\n            kind, name, _path = self._current_item\n            self._logger.warning(\n                \"Installed %s PKI object '%s' through TFTP after config installation failed\",\n                kind,\n                name,\n            )\n            self._fallback_active = False\n            self._config_failed = False\n            self._current_item = None\n            self._submit_next()\n            return\n        if self._config_failed:\n            self._submit_tftp_fallback()\n            return\n        self._current_item = None\n        self._submit_next()\n\n    @property\n    def completion_message(self):\n        return None",
        "lineStart": 1,
        "lineEnd": 471,
        "totalLines": 471,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716551402,
      "end": 1793716551415
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d67ef9001cVqvknYkrEUlkx",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d672ec0016X1lLBjAUdzQBg",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 22776,
    "input": 5361,
    "output": 76,
    "reasoning": 187,
    "cache": {
      "read": 17152,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d672ec0016X1lLBjAUdzQBg",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716548332,
    "completed": 1793716551420
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 22776,
    "input": 5361,
    "output": 76,
    "reasoning": 187,
    "cache": {
      "read": 17152,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 27
step-start
{
  "type": "step-start",
  "id": "prt_1a1d686f7001r0jLQQb5VabCog",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d67f02001f8lG7xsSMGR7pA"
}
Reasoning
Now, remaining: tests and READMEs. Let me read the tests I haven't fully read:
- test_common_stack_boundaries.py (full)
- test_common_terminal_driver.py offset 600
- test_common_stack_parsing.py (I read the first part; get full)
- test_common_admin_credentials.py, test_common_recovery.py, test_common_scope_errors.py (truncated reads; need the rest)
- READMEs

Let me batch reads. First check file sizes by reading fully (2000 line default). Let me batch: test_common_stack_boundaries.py, test_common_terminal_driver.py offset 600, test_common_stack_parsing.py offset ~? I don't know where it truncated. I'll just read whole files again (they're probably under 2000 lines each — but truncated earlier at some point? The summary says truncated reads). To be safe, read each test file with offset where needed. Actually simplest: read each file fully with default limit (2000 lines). If any exceed 2000 lines, read the remainder.

Batch 1: test_common_stack_boundaries.py (full), test_common_stack_parsing.py (full), test_common_terminal_driver.py (offset 600, limit 2000).
Now the test files and READMEs.
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_stack_boundaries.py"
}

Output

<path>/source/head/fortinet/tests/test_common_stack_boundaries.py</path>
<type>file</type>
<content>
1: """Generated end-to-end boundary cases for the FortiOS serial parser stack."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from unittest.mock import MagicMock, patch
7: 
8: REPO_ROOT = Path(__file__).resolve().parents[2]
9: sys.path.insert(0, str(REPO_ROOT))
10: 
11: from fortinet.common.cli_commands import CommandSpec, SessionLossAction  # noqa: E402
12: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
13: from fortinet.common.features.base import Feature  # noqa: E402
14: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
15: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
16: from fortinet.common.terminal import Terminal  # noqa: E402
17: from fortinet.tests.test_common_stack_parsing import (  # noqa: E402
18:     SerialConnection,
19: )
20: 
21: 
22: class BoundaryFeature(Feature):
23:     def __init__(self, commander, spec):
24:         super().__init__(None, commander, "boundary-probe")
25:         self.spec = spec
26:         self.outputs = []
27:         self.dispatched = []
28: 
29:     def activate(self):
30:         self.commander.submit_block(self, self.spec)
31: 
32:     def on_command_dispatched(self, attempt):
33:         super().on_command_dispatched(attempt)
34:         self.dispatched.append(attempt)
35: 
36:     def on_command_executed(self, attempt, state):
37:         self.outputs.append((bytes(attempt.output), state))
38: 
39:     def on_session_loss(self, attempt):
40:         return SessionLossAction.CONTINUE
41: 
42: 
43: def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b"fw #"):
44:     logger = MagicMock()
45:     connection = SerialConnection({
46:         b"admin\r": b"Password:",
47:         b"secret\r": b"Welcome!\r\n" + initial_prompt + b"\r\n",
48:         b"probe\r": response,
49:     })
50:     terminal = Terminal(connection, logger, default_wait="fw #")
51:     commander = FOSCommander(terminal, logger)
52:     feature = BoundaryFeature(commander, spec)
53:     commander.start([feature])
54:     driver = FOSCliDriver(
55:         terminal,
56:         commander,
57:         Credentials("admin", "secret"),
58:         logger,
59:         "Bootstrap1!",
60:         MagicMock(),
61:         MagicMock(),
62:         allow_credential_recovery=allow_recovery,
63:     )
64:     if allow_recovery:
65:         driver.remember_current_credentials()
66:     states = []
67:     original_on_state = commander.on_state
68:     def record_state(state, output):
69:         states.append(state)
70:         return original_on_state(state, output)
71:     commander.on_state = record_state
72:     original_echo = commander.on_prompt_echo
73:     def record_echo(output):
74:         states.append(FOSCliState.CMD_PROMPT_ECHO)
75:         return original_echo(output)
76:     commander.on_prompt_echo = record_echo
77:     return connection, terminal, commander, driver, feature, states
78: 
79: def prompt_case(hostname, context, marker, ending):
80:     prompt = hostname + context + " " + marker
81:     response = (
82:         (prompt + " probe" + ending + "captured diagnostic" + ending + prompt + ending)
83:         .encode()
84:     )
85:     spec = CommandSpec("probe", capture_output=True)
86:     connection, terminal, commander, driver, feature, states = make_stack(
87:         spec, response, initial_prompt=prompt.encode()
88:     )
89:     try:
90:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
91:                 patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
92:             driver.process_state()
93:         assert commander.ready
94:         assert feature.completed
95:         assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT
96:         assert b"captured diagnostic" in feature.outputs[0][0]
97:         assert FOSCliState.CMD_PROMPT_ECHO in states
98:     finally:
99:         if not connection.closed:
100:             terminal.close()
101: 
102: 
103: def state_case(state, sample, suffix=b"", *, recover=False):
104:     response = sample + suffix
105:     if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):
106:         completion = (FOSCliState.CMD_PROMPT,)
107:     elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):
108:         completion = (FOSCliState.CMD_PROMPT,)
109:     else:
110:         completion = (state,)
111:     connection, terminal, commander, driver, feature, states = make_stack(
112:         CommandSpec("probe", completion_states=completion, capture_output=True),
113:         response,
114:         allow_recovery=recover,
115:         initial_prompt=b"fw (global) #" if state == FOSCliState.CMD_PROMPT_ECHO else b"fw #",
116:     )
117:     try:
118:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.03), \
119:                 patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
120:             driver.process_state()
121:         assert state in states
122:         assert commander.ready
123:         assert feature.completed
124:     finally:
125:         if not connection.closed:
126:             terminal.close()
127: 
128: 
129: class EndToEndBoundaryCases(unittest.TestCase):
130:     def test_expected_completion_prompt_mismatch_raises_from_serial_result(self):
131:         response = b"Do you want to continue?\r\n"
132:         connection, terminal, _commander, driver, _feature, _states = make_stack(
133:             CommandSpec(
134:                 "probe",
135:                 completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),
136:                 expected_completion_state=FOSCliState.CMD_PROMPT,
137:             ),
138:             response,
139:         )
140:         try:
141:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
142:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
143:                 with self.assertRaisesRegex(RuntimeError, "expected CMD_PROMPT, received CONFIRMATION"):
144:                     driver.process_state()
145:         finally:
146:             terminal.close()
147: 
148:     def test_error_text_is_captured_when_fail_on_error_is_disabled(self):
149:         response = b"Command fail. Return code -542\r\nfw #\r\n"
150:         connection, terminal, commander, driver, feature, _states = make_stack(
151:             CommandSpec("probe", capture_output=True, fail_on_error=False), response
152:         )
153:         try:
154:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
155:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
156:                 driver.process_state()
157:             self.assertTrue(commander.ready)
158:             self.assertTrue(feature.completed)
159:             self.assertIn(b"Command fail. Return code -542", feature.outputs[0][0])
160:         finally:
161:             if not connection.closed:
162:                 terminal.close()
163: 
164:     def test_noise_without_a_pattern_reaches_unknown_then_timeout(self):
165:         connection, terminal, commander, driver, feature, states = make_stack(
166:             CommandSpec("probe", capture_output=True), b"\xff\x00garbage\r\nnot-a-prompt\r\n"
167:         )
168:         try:
169:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
170:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.06):
171:                 driver.process_state()
172:             self.assertIn(FOSCliState.UNKNOWN, states)
173:             self.assertIn(FOSCliState.TN_TIMEOUT, states)
174:             self.assertFalse(commander.ready)
175:             self.assertFalse(feature.completed)
176:             self.assertIn(b"garbage", bytes(feature.current_attempt.output))
177:         finally:
178:             terminal.close()
179: 
180:     def test_idle_read_exposes_retained_prompt_newline(self):
181:         connection, terminal, commander, driver, feature, states = make_stack(
182:             CommandSpec("probe", capture_output=True), None
183:         )
184:         try:
185:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
186:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.04):
187:                 driver.process_state()
188:             self.assertIn(FOSCliState.TN_TIMEOUT, states)
189:             # The login response ended with a newline after the matched CLI
190:             # prompt. Full-buffer timeout inspection exposes that real byte.
191:             self.assertEqual(bytes(feature.current_attempt.output), b"\n")
192:             self.assertTrue(commander.busy)
193:         finally:
194:             terminal.close()
195: 
196:     def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):
197:         command_echo = b"fw (global) # probe\r\n"
198:         payload = b"config system dns\r\n set primary 1.1.1.1\r\nend\r\nfw (global) #\r\n"
199:         response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])
200:         connection, terminal, commander, driver, feature, states = make_stack(
201:             CommandSpec("probe", capture_output=True), response,
202:             initial_prompt=b"fw (global) #",
203:         )
204:         try:
205:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
206:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
207:                 driver.process_state()
208:             self.assertTrue(commander.ready)
209:             self.assertIn(FOSCliState.CMD_PROMPT_ECHO, states)
210:             self.assertIn(b"set primary 1.1.1.1", feature.outputs[0][0])
211:         finally:
212:             if not connection.closed:
213:                 terminal.close()
214: 
215: 
216: # Exercise every pattern-backed state through the real terminal, driver, and
217: # commander. States that represent a login transition include the follow-up
218: # prompt needed for the real scheduler to safely finish the feature.
219: STATE_CASES = [
220:     ("username_prompt", FOSCliState.PROVIDE_USERNAME, b"fw login:\r\n", b"Password:\r\nWelcome!\r\nfw #\r\n", False),
221:     ("password_prompt", FOSCliState.PROVIDE_PASSWORD, b"Password:", b"", False),
222:     ("new_password_prompt", FOSCliState.CHANGE_PASSWORD, b"New Password:", b"", False),
223:     ("credential_rejected", FOSCliState.CREDENTIAL_REJECTED, b"Login incorrect\r\n", b"fw login:\r\nPassword:\r\nWelcome!\r\nfw #\r\n", True),
224:     ("credential_accepted", FOSCliState.CREDENTIAL_ACCEPTED, b"Welcome!\r\n", b"fw #\r\n", False),
225:     ("license_failure_notice", FOSCliState.LIC_FAIL, b"VM license install failed.\r\n", b"", False),
226:     ("command_prompt", FOSCliState.CMD_PROMPT, b"fw #\r\n", b"", False),
227:     ("command_prompt_echo", FOSCliState.CMD_PROMPT_ECHO, b"fw (global) # probe\r\n", b"fw (global) #\r\n", False),
228:     ("shutdown_notice", FOSCliState.SHUTTING_DOWN, b"system is going down\r\n", b"", False),
229:     ("reboot_notice", FOSCliState.REBOOTING, b"stand by while rebooting\r\n", b"", False),
230:     ("session_lost_notice", FOSCliState.SESSION_LOST, b"*ATTENTION*: Admin sessions removed because license registration status changed\r\n", b"Welcome!\r\nfw #\r\n", False),
231:     ("current_password_prompt", FOSCliState.CURRENT_PASSWORD, b"Current Password:\r\n", b"", False),
232:     ("confirmation_prompt", FOSCliState.CONFIRMATION, b"Do you want to continue?\r\n", b"", False),
233:     ("confirm_new_password_prompt", FOSCliState.CHANGE_PASSWORD_CONFIRM, b"Confirm Password:\r\n", b"", False),
234:     ("pager_prompt", FOSCliState.MORE_PROMPT, b"--More--", b"", False),
235:     ("multiline_prompt", FOSCliState.MULTILINE_PROMPT, b">\r\n", b"", False),
236: ]
237: 
238: 
239: def _make_state_test(case):
240:     name, state, sample, suffix, recover = case
241:     def test(self):
242:         with self.subTest(state=state.name):
243:             state_case(state, sample, suffix, recover=recover)
244:     test.__name__ = f"test_state_{name}_through_full_stack"
245:     test.__doc__ = f"Reach {state.name} from connection bytes and observe commander handling."
246:     return test
247: 
248: 
249: for _case in STATE_CASES:
250:     setattr(EndToEndBoundaryCases, f"test_state_{_case[0]}_through_full_stack", _make_state_test(_case))
251: 
252: 
253: # Hostname, prompt context, prompt glyph, and line ending are independent
254: # parser boundaries. The Cartesian set creates one discoverable test per wire
255: # shape so failures point to the exact prompt form.
256: PROMPT_CASES = [
257:     (host, context, marker, ending)
258:     for host in ("fw", "edge-01", "FortiGate-VM64-KVM", "FGVMABC123")
259:     for context in ("", " (global)", " (root) (vdom blue)")
260:     for marker in ("#", "$")
261:     for ending in ("\n", "\r\n")
262: ]
263: 
264: 
265: def _make_prompt_test(case):
266:     hostname, context, marker, ending = case
267:     label = f"{hostname}_{context or 'plain'}_{marker}_{'crlf' if ending == chr(13)+chr(10) else 'lf'}"
268:     def test(self):
269:         prompt_case(hostname, context, marker, ending)
270:     test.__name__ = "test_prompt_" + "_".join(part.replace(" ", "").replace("(", "").replace(")", "") for part in label.split("_"))
271:     test.__doc__ = f"Parse command echo and prompt {hostname}{context} {marker} with {ending!r}."
272:     return test
273: 
274: 
275: for _case in PROMPT_CASES:
276:     setattr(EndToEndBoundaryCases, _make_prompt_test(_case).__name__, _make_prompt_test(_case))
277: 
278: 
279: # Distinct failure payloads ensure the command failure parser handles signed
280: # and unsigned return codes and optional whitespace over the serial boundary.
281: ERROR_CASES = [b"0", b"1", b"-1", b"-5", b"-542", b"255", b"0007", b"-214"]
282: 
283: 
284: def _make_failure_test(return_code):
285:     def test(self):
286:         response = b"Command fail. Return code " + return_code + b"\r\nfw #\r\n"
287:         connection, terminal, _commander, driver, _feature, _states = make_stack(
288:             CommandSpec("probe", capture_output=True, fail_on_error=True), response
289:         )
290:         try:
291:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
292:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
293:                 with self.assertRaisesRegex(RuntimeError, f"return code {return_code.decode()}"):
294:                     driver.process_state()
295:         finally:
296:             terminal.close()
297:     test.__name__ = f"test_command_error_code_{return_code.decode().replace('-', 'negative_')}"
298:     test.__doc__ = f"Pass FortiOS return code {return_code.decode()} through the full stack."
299:     return test
300: 
301: 
302: for _code in ERROR_CASES:
303:     setattr(EndToEndBoundaryCases, _make_failure_test(_code).__name__, _make_failure_test(_code))
304: 
305: 
306: CAPTURE_CASES = [
307:     b"one line\n",
308:     b"multiple\nlines\nwith trailing newline\n",
309:     b"carriage return\rwithout line feed",
310:     b"\xff\xfe\x00binary-ish bytes",
311:     b"\x1b[31mcolored output\x1b[0m",
312:     b"tabs\tand    repeated spaces",
313:     b"# metadata-looking output",
314:     b"prompt-like value fw (global) # inside data",
315:     b"empty-looking\n\nline",
316:     b"unicode utf-8: \xe2\x98\x83",
317:     b"long" * 2048,
318:     b"return code text: Command fail. Return code -7",
319: ]
320: 
321: 
322: def _make_capture_test(index, payload):
323:     def test(self):
324:         ending = b"\r\n"
325:         response = payload + ending + b"fw #\r\n"
326:         connection, terminal, commander, driver, feature, _states = make_stack(
327:             CommandSpec("probe", capture_output=True), response
328:         )
329:         try:
330:             with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
331:                     patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
332:                 driver.process_state()
333:             self.assertTrue(commander.ready)
334:             self.assertEqual(feature.outputs[0][1], FOSCliState.CMD_PROMPT)
335:             self.assertIn(payload, feature.outputs[0][0])
336:         finally:
337:             if not connection.closed:
338:                 terminal.close()
339:     test.__name__ = f"test_capture_payload_{index:02d}"
340:     test.__doc__ = f"Capture serial output payload case {index}."
341:     return test
342: 
343: 
344: for _index, _payload in enumerate(CAPTURE_CASES):
345:     setattr(EndToEndBoundaryCases, f"test_capture_payload_{_index:02d}", _make_capture_test(_index, _payload))
346: 
347: 
348: if __name__ == "__main__":
349:     unittest.main()

(End of file - total 349 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d68f23001nRo3LdlYOduIux",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d67f02001f8lG7xsSMGR7pA",
  "callID": "call_e60c29a847eb4402a880e463",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_stack_boundaries.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_stack_boundaries.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Generated end-to-end boundary cases for the FortiOS serial parser stack.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from unittest.mock import MagicMock, patch\n7: \n8: REPO_ROOT = Path(__file__).resolve().parents[2]\n9: sys.path.insert(0, str(REPO_ROOT))\n10: \n11: from fortinet.common.cli_commands import CommandSpec, SessionLossAction  # noqa: E402\n12: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n13: from fortinet.common.features.base import Feature  # noqa: E402\n14: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n15: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n16: from fortinet.common.terminal import Terminal  # noqa: E402\n17: from fortinet.tests.test_common_stack_parsing import (  # noqa: E402\n18:     SerialConnection,\n19: )\n20: \n21: \n22: class BoundaryFeature(Feature):\n23:     def __init__(self, commander, spec):\n24:         super().__init__(None, commander, \"boundary-probe\")\n25:         self.spec = spec\n26:         self.outputs = []\n27:         self.dispatched = []\n28: \n29:     def activate(self):\n30:         self.commander.submit_block(self, self.spec)\n31: \n32:     def on_command_dispatched(self, attempt):\n33:         super().on_command_dispatched(attempt)\n34:         self.dispatched.append(attempt)\n35: \n36:     def on_command_executed(self, attempt, state):\n37:         self.outputs.append((bytes(attempt.output), state))\n38: \n39:     def on_session_loss(self, attempt):\n40:         return SessionLossAction.CONTINUE\n41: \n42: \n43: def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n44:     logger = MagicMock()\n45:     connection = SerialConnection({\n46:         b\"admin\\r\": b\"Password:\",\n47:         b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n48:         b\"probe\\r\": response,\n49:     })\n50:     terminal = Terminal(connection, logger, default_wait=\"fw #\")\n51:     commander = FOSCommander(terminal, logger)\n52:     feature = BoundaryFeature(commander, spec)\n53:     commander.start([feature])\n54:     driver = FOSCliDriver(\n55:         terminal,\n56:         commander,\n57:         Credentials(\"admin\", \"secret\"),\n58:         logger,\n59:         \"Bootstrap1!\",\n60:         MagicMock(),\n61:         MagicMock(),\n62:         allow_credential_recovery=allow_recovery,\n63:     )\n64:     if allow_recovery:\n65:         driver.remember_current_credentials()\n66:     states = []\n67:     original_on_state = commander.on_state\n68:     def record_state(state, output):\n69:         states.append(state)\n70:         return original_on_state(state, output)\n71:     commander.on_state = record_state\n72:     original_echo = commander.on_prompt_echo\n73:     def record_echo(output):\n74:         states.append(FOSCliState.CMD_PROMPT_ECHO)\n75:         return original_echo(output)\n76:     commander.on_prompt_echo = record_echo\n77:     return connection, terminal, commander, driver, feature, states\n78: \n79: def prompt_case(hostname, context, marker, ending):\n80:     prompt = hostname + context + \" \" + marker\n81:     response = (\n82:         (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n83:         .encode()\n84:     )\n85:     spec = CommandSpec(\"probe\", capture_output=True)\n86:     connection, terminal, commander, driver, feature, states = make_stack(\n87:         spec, response, initial_prompt=prompt.encode()\n88:     )\n89:     try:\n90:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n91:                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n92:             driver.process_state()\n93:         assert commander.ready\n94:         assert feature.completed\n95:         assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT\n96:         assert b\"captured diagnostic\" in feature.outputs[0][0]\n97:         assert FOSCliState.CMD_PROMPT_ECHO in states\n98:     finally:\n99:         if not connection.closed:\n100:             terminal.close()\n101: \n102: \n103: def state_case(state, sample, suffix=b\"\", *, recover=False):\n104:     response = sample + suffix\n105:     if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):\n106:         completion = (FOSCliState.CMD_PROMPT,)\n107:     elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):\n108:         completion = (FOSCliState.CMD_PROMPT,)\n109:     else:\n110:         completion = (state,)\n111:     connection, terminal, commander, driver, feature, states = make_stack(\n112:         CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n113:         response,\n114:         allow_recovery=recover,\n115:         initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n116:     )\n117:     try:\n118:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n119:                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n120:             driver.process_state()\n121:         assert state in states\n122:         assert commander.ready\n123:         assert feature.completed\n124:     finally:\n125:         if not connection.closed:\n126:             terminal.close()\n127: \n128: \n129: class EndToEndBoundaryCases(unittest.TestCase):\n130:     def test_expected_completion_prompt_mismatch_raises_from_serial_result(self):\n131:         response = b\"Do you want to continue?\\r\\n\"\n132:         connection, terminal, _commander, driver, _feature, _states = make_stack(\n133:             CommandSpec(\n134:                 \"probe\",\n135:                 completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),\n136:                 expected_completion_state=FOSCliState.CMD_PROMPT,\n137:             ),\n138:             response,\n139:         )\n140:         try:\n141:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n142:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n143:                 with self.assertRaisesRegex(RuntimeError, \"expected CMD_PROMPT, received CONFIRMATION\"):\n144:                     driver.process_state()\n145:         finally:\n146:             terminal.close()\n147: \n148:     def test_error_text_is_captured_when_fail_on_error_is_disabled(self):\n149:         response = b\"Command fail. Return code -542\\r\\nfw #\\r\\n\"\n150:         connection, terminal, commander, driver, feature, _states = make_stack(\n151:             CommandSpec(\"probe\", capture_output=True, fail_on_error=False), response\n152:         )\n153:         try:\n154:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n155:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n156:                 driver.process_state()\n157:             self.assertTrue(commander.ready)\n158:             self.assertTrue(feature.completed)\n159:             self.assertIn(b\"Command fail. Return code -542\", feature.outputs[0][0])\n160:         finally:\n161:             if not connection.closed:\n162:                 terminal.close()\n163: \n164:     def test_noise_without_a_pattern_reaches_unknown_then_timeout(self):\n165:         connection, terminal, commander, driver, feature, states = make_stack(\n166:             CommandSpec(\"probe\", capture_output=True), b\"\\xff\\x00garbage\\r\\nnot-a-prompt\\r\\n\"\n167:         )\n168:         try:\n169:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n170:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.06):\n171:                 driver.process_state()\n172:             self.assertIn(FOSCliState.UNKNOWN, states)\n173:             self.assertIn(FOSCliState.TN_TIMEOUT, states)\n174:             self.assertFalse(commander.ready)\n175:             self.assertFalse(feature.completed)\n176:             self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n177:         finally:\n178:             terminal.close()\n179: \n180:     def test_idle_read_exposes_retained_prompt_newline(self):\n181:         connection, terminal, commander, driver, feature, states = make_stack(\n182:             CommandSpec(\"probe\", capture_output=True), None\n183:         )\n184:         try:\n185:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n186:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n187:                 driver.process_state()\n188:             self.assertIn(FOSCliState.TN_TIMEOUT, states)\n189:             # The login response ended with a newline after the matched CLI\n190:             # prompt. Full-buffer timeout inspection exposes that real byte.\n191:             self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n192:             self.assertTrue(commander.busy)\n193:         finally:\n194:             terminal.close()\n195: \n196:     def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n197:         command_echo = b\"fw (global) # probe\\r\\n\"\n198:         payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n199:         response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n200:         connection, terminal, commander, driver, feature, states = make_stack(\n201:             CommandSpec(\"probe\", capture_output=True), response,\n202:             initial_prompt=b\"fw (global) #\",\n203:         )\n204:         try:\n205:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n206:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n207:                 driver.process_state()\n208:             self.assertTrue(commander.ready)\n209:             self.assertIn(FOSCliState.CMD_PROMPT_ECHO, states)\n210:             self.assertIn(b\"set primary 1.1.1.1\", feature.outputs[0][0])\n211:         finally:\n212:             if not connection.closed:\n213:                 terminal.close()\n214: \n215: \n216: # Exercise every pattern-backed state through the real terminal, driver, and\n217: # commander. States that represent a login transition include the follow-up\n218: # prompt needed for the real scheduler to safely finish the feature.\n219: STATE_CASES = [\n220:     (\"username_prompt\", FOSCliState.PROVIDE_USERNAME, b\"fw login:\\r\\n\", b\"Password:\\r\\nWelcome!\\r\\nfw #\\r\\n\", False),\n221:     (\"password_prompt\", FOSCliState.PROVIDE_PASSWORD, b\"Password:\", b\"\", False),\n222:     (\"new_password_prompt\", FOSCliState.CHANGE_PASSWORD, b\"New Password:\", b\"\", False),\n223:     (\"credential_rejected\", FOSCliState.CREDENTIAL_REJECTED, b\"Login incorrect\\r\\n\", b\"fw login:\\r\\nPassword:\\r\\nWelcome!\\r\\nfw #\\r\\n\", True),\n224:     (\"credential_accepted\", FOSCliState.CREDENTIAL_ACCEPTED, b\"Welcome!\\r\\n\", b\"fw #\\r\\n\", False),\n225:     (\"license_failure_notice\", FOSCliState.LIC_FAIL, b\"VM license install failed.\\r\\n\", b\"\", False),\n226:     (\"command_prompt\", FOSCliState.CMD_PROMPT, b\"fw #\\r\\n\", b\"\", False),\n227:     (\"command_prompt_echo\", FOSCliState.CMD_PROMPT_ECHO, b\"fw (global) # probe\\r\\n\", b\"fw (global) #\\r\\n\", False),\n228:     (\"shutdown_notice\", FOSCliState.SHUTTING_DOWN, b\"system is going down\\r\\n\", b\"\", False),\n229:     (\"reboot_notice\", FOSCliState.REBOOTING, b\"stand by while rebooting\\r\\n\", b\"\", False),\n230:     (\"session_lost_notice\", FOSCliState.SESSION_LOST, b\"*ATTENTION*: Admin sessions removed because license registration status changed\\r\\n\", b\"Welcome!\\r\\nfw #\\r\\n\", False),\n231:     (\"current_password_prompt\", FOSCliState.CURRENT_PASSWORD, b\"Current Password:\\r\\n\", b\"\", False),\n232:     (\"confirmation_prompt\", FOSCliState.CONFIRMATION, b\"Do you want to continue?\\r\\n\", b\"\", False),\n233:     (\"confirm_new_password_prompt\", FOSCliState.CHANGE_PASSWORD_CONFIRM, b\"Confirm Password:\\r\\n\", b\"\", False),\n234:     (\"pager_prompt\", FOSCliState.MORE_PROMPT, b\"--More--\", b\"\", False),\n235:     (\"multiline_prompt\", FOSCliState.MULTILINE_PROMPT, b\">\\r\\n\", b\"\", False),\n236: ]\n237: \n238: \n239: def _make_state_test(case):\n240:     name, state, sample, suffix, recover = case\n241:     def test(self):\n242:         with self.subTest(state=state.name):\n243:             state_case(state, sample, suffix, recover=recover)\n244:     test.__name__ = f\"test_state_{name}_through_full_stack\"\n245:     test.__doc__ = f\"Reach {state.name} from connection bytes and observe commander handling.\"\n246:     return test\n247: \n248: \n249: for _case in STATE_CASES:\n250:     setattr(EndToEndBoundaryCases, f\"test_state_{_case[0]}_through_full_stack\", _make_state_test(_case))\n251: \n252: \n253: # Hostname, prompt context, prompt glyph, and line ending are independent\n254: # parser boundaries. The Cartesian set creates one discoverable test per wire\n255: # shape so failures point to the exact prompt form.\n256: PROMPT_CASES = [\n257:     (host, context, marker, ending)\n258:     for host in (\"fw\", \"edge-01\", \"FortiGate-VM64-KVM\", \"FGVMABC123\")\n259:     for context in (\"\", \" (global)\", \" (root) (vdom blue)\")\n260:     for marker in (\"#\", \"$\")\n261:     for ending in (\"\\n\", \"\\r\\n\")\n262: ]\n263: \n264: \n265: def _make_prompt_test(case):\n266:     hostname, context, marker, ending = case\n267:     label = f\"{hostname}_{context or 'plain'}_{marker}_{'crlf' if ending == chr(13)+chr(10) else 'lf'}\"\n268:     def test(self):\n269:         prompt_case(hostname, context, marker, ending)\n270:     test.__name__ = \"test_prompt_\" + \"_\".join(part.replace(\" \", \"\").replace(\"(\", \"\").replace(\")\", \"\") for part in label.split(\"_\"))\n271:     test.__doc__ = f\"Parse command echo and prompt {hostname}{context} {marker} with {ending!r}.\"\n272:     return test\n273: \n274: \n275: for _case in PROMPT_CASES:\n276:     setattr(EndToEndBoundaryCases, _make_prompt_test(_case).__name__, _make_prompt_test(_case))\n277: \n278: \n279: # Distinct failure payloads ensure the command failure parser handles signed\n280: # and unsigned return codes and optional whitespace over the serial boundary.\n281: ERROR_CASES = [b\"0\", b\"1\", b\"-1\", b\"-5\", b\"-542\", b\"255\", b\"0007\", b\"-214\"]\n282: \n283: \n284: def _make_failure_test(return_code):\n285:     def test(self):\n286:         response = b\"Command fail. Return code \" + return_code + b\"\\r\\nfw #\\r\\n\"\n287:         connection, terminal, _commander, driver, _feature, _states = make_stack(\n288:             CommandSpec(\"probe\", capture_output=True, fail_on_error=True), response\n289:         )\n290:         try:\n291:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n292:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n293:                 with self.assertRaisesRegex(RuntimeError, f\"return code {return_code.decode()}\"):\n294:                     driver.process_state()\n295:         finally:\n296:             terminal.close()\n297:     test.__name__ = f\"test_command_error_code_{return_code.decode().replace('-', 'negative_')}\"\n298:     test.__doc__ = f\"Pass FortiOS return code {return_code.decode()} through the full stack.\"\n299:     return test\n300: \n301: \n302: for _code in ERROR_CASES:\n303:     setattr(EndToEndBoundaryCases, _make_failure_test(_code).__name__, _make_failure_test(_code))\n304: \n305: \n306: CAPTURE_CASES = [\n307:     b\"one line\\n\",\n308:     b\"multiple\\nlines\\nwith trailing newline\\n\",\n309:     b\"carriage return\\rwithout line feed\",\n310:     b\"\\xff\\xfe\\x00binary-ish bytes\",\n311:     b\"\\x1b[31mcolored output\\x1b[0m\",\n312:     b\"tabs\\tand    repeated spaces\",\n313:     b\"# metadata-looking output\",\n314:     b\"prompt-like value fw (global) # inside data\",\n315:     b\"empty-looking\\n\\nline\",\n316:     b\"unicode utf-8: \\xe2\\x98\\x83\",\n317:     b\"long\" * 2048,\n318:     b\"return code text: Command fail. Return code -7\",\n319: ]\n320: \n321: \n322: def _make_capture_test(index, payload):\n323:     def test(self):\n324:         ending = b\"\\r\\n\"\n325:         response = payload + ending + b\"fw #\\r\\n\"\n326:         connection, terminal, commander, driver, feature, _states = make_stack(\n327:             CommandSpec(\"probe\", capture_output=True), response\n328:         )\n329:         try:\n330:             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n331:                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n332:                 driver.process_state()\n333:             self.assertTrue(commander.ready)\n334:             self.assertEqual(feature.outputs[0][1], FOSCliState.CMD_PROMPT)\n335:             self.assertIn(payload, feature.outputs[0][0])\n336:         finally:\n337:             if not connection.closed:\n338:                 terminal.close()\n339:     test.__name__ = f\"test_capture_payload_{index:02d}\"\n340:     test.__doc__ = f\"Capture serial output payload case {index}.\"\n341:     return test\n342: \n343: \n344: for _index, _payload in enumerate(CAPTURE_CASES):\n345:     setattr(EndToEndBoundaryCases, f\"test_capture_payload_{_index:02d}\", _make_capture_test(_index, _payload))\n346: \n347: \n348: if __name__ == \"__main__\":\n349:     unittest.main()\n\n(End of file - total 349 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_stack_boundaries.py",
    "metadata": {
      "preview": "\"\"\"Generated end-to-end boundary cases for the FortiOS serial parser stack.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock, patch\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import CommandSpec, SessionLossAction  # noqa: E402\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\nfrom fortinet.tests.test_common_stack_parsing import (  # noqa: E402\n    SerialConnection,\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_stack_boundaries.py",
        "text": "\"\"\"Generated end-to-end boundary cases for the FortiOS serial parser stack.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock, patch\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import CommandSpec, SessionLossAction  # noqa: E402\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\nfrom fortinet.tests.test_common_stack_parsing import (  # noqa: E402\n    SerialConnection,\n)\n\n\nclass BoundaryFeature(Feature):\n    def __init__(self, commander, spec):\n        super().__init__(None, commander, \"boundary-probe\")\n        self.spec = spec\n        self.outputs = []\n        self.dispatched = []\n\n    def activate(self):\n        self.commander.submit_block(self, self.spec)\n\n    def on_command_dispatched(self, attempt):\n        super().on_command_dispatched(attempt)\n        self.dispatched.append(attempt)\n\n    def on_command_executed(self, attempt, state):\n        self.outputs.append((bytes(attempt.output), state))\n\n    def on_session_loss(self, attempt):\n        return SessionLossAction.CONTINUE\n\n\ndef make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n    logger = MagicMock()\n    connection = SerialConnection({\n        b\"admin\\r\": b\"Password:\",\n        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n        b\"probe\\r\": response,\n    })\n    terminal = Terminal(connection, logger, default_wait=\"fw #\")\n    commander = FOSCommander(terminal, logger)\n    feature = BoundaryFeature(commander, spec)\n    commander.start([feature])\n    driver = FOSCliDriver(\n        terminal,\n        commander,\n        Credentials(\"admin\", \"secret\"),\n        logger,\n        \"Bootstrap1!\",\n        MagicMock(),\n        MagicMock(),\n        allow_credential_recovery=allow_recovery,\n    )\n    if allow_recovery:\n        driver.remember_current_credentials()\n    states = []\n    original_on_state = commander.on_state\n    def record_state(state, output):\n        states.append(state)\n        return original_on_state(state, output)\n    commander.on_state = record_state\n    original_echo = commander.on_prompt_echo\n    def record_echo(output):\n        states.append(FOSCliState.CMD_PROMPT_ECHO)\n        return original_echo(output)\n    commander.on_prompt_echo = record_echo\n    return connection, terminal, commander, driver, feature, states\n\ndef prompt_case(hostname, context, marker, ending):\n    prompt = hostname + context + \" \" + marker\n    response = (\n        (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n        .encode()\n    )\n    spec = CommandSpec(\"probe\", capture_output=True)\n    connection, terminal, commander, driver, feature, states = make_stack(\n        spec, response, initial_prompt=prompt.encode()\n    )\n    try:\n        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n            driver.process_state()\n        assert commander.ready\n        assert feature.completed\n        assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT\n        assert b\"captured diagnostic\" in feature.outputs[0][0]\n        assert FOSCliState.CMD_PROMPT_ECHO in states\n    finally:\n        if not connection.closed:\n            terminal.close()\n\n\ndef state_case(state, sample, suffix=b\"\", *, recover=False):\n    response = sample + suffix\n    if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):\n        completion = (FOSCliState.CMD_PROMPT,)\n    elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):\n        completion = (FOSCliState.CMD_PROMPT,)\n    else:\n        completion = (state,)\n    connection, terminal, commander, driver, feature, states = make_stack(\n        CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n        response,\n        allow_recovery=recover,\n        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n    )\n    try:\n        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n            driver.process_state()\n        assert state in states\n        assert commander.ready\n        assert feature.completed\n    finally:\n        if not connection.closed:\n            terminal.close()\n\n\nclass EndToEndBoundaryCases(unittest.TestCase):\n    def test_expected_completion_prompt_mismatch_raises_from_serial_result(self):\n        response = b\"Do you want to continue?\\r\\n\"\n        connection, terminal, _commander, driver, _feature, _states = make_stack(\n            CommandSpec(\n                \"probe\",\n                completion_states=(FOSCliState.CONFIRMATION, FOSCliState.CMD_PROMPT),\n                expected_completion_state=FOSCliState.CMD_PROMPT,\n            ),\n            response,\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                with self.assertRaisesRegex(RuntimeError, \"expected CMD_PROMPT, received CONFIRMATION\"):\n                    driver.process_state()\n        finally:\n            terminal.close()\n\n    def test_error_text_is_captured_when_fail_on_error_is_disabled(self):\n        response = b\"Command fail. Return code -542\\r\\nfw #\\r\\n\"\n        connection, terminal, commander, driver, feature, _states = make_stack(\n            CommandSpec(\"probe\", capture_output=True, fail_on_error=False), response\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                driver.process_state()\n            self.assertTrue(commander.ready)\n            self.assertTrue(feature.completed)\n            self.assertIn(b\"Command fail. Return code -542\", feature.outputs[0][0])\n        finally:\n            if not connection.closed:\n                terminal.close()\n\n    def test_noise_without_a_pattern_reaches_unknown_then_timeout(self):\n        connection, terminal, commander, driver, feature, states = make_stack(\n            CommandSpec(\"probe\", capture_output=True), b\"\\xff\\x00garbage\\r\\nnot-a-prompt\\r\\n\"\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.06):\n                driver.process_state()\n            self.assertIn(FOSCliState.UNKNOWN, states)\n            self.assertIn(FOSCliState.TN_TIMEOUT, states)\n            self.assertFalse(commander.ready)\n            self.assertFalse(feature.completed)\n            self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n        finally:\n            terminal.close()\n\n    def test_idle_read_exposes_retained_prompt_newline(self):\n        connection, terminal, commander, driver, feature, states = make_stack(\n            CommandSpec(\"probe\", capture_output=True), None\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n                driver.process_state()\n            self.assertIn(FOSCliState.TN_TIMEOUT, states)\n            # The login response ended with a newline after the matched CLI\n            # prompt. Full-buffer timeout inspection exposes that real byte.\n            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n            self.assertTrue(commander.busy)\n        finally:\n            terminal.close()\n\n    def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n        command_echo = b\"fw (global) # probe\\r\\n\"\n        payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n        response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n        connection, terminal, commander, driver, feature, states = make_stack(\n            CommandSpec(\"probe\", capture_output=True), response,\n            initial_prompt=b\"fw (global) #\",\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                driver.process_state()\n            self.assertTrue(commander.ready)\n            self.assertIn(FOSCliState.CMD_PROMPT_ECHO, states)\n            self.assertIn(b\"set primary 1.1.1.1\", feature.outputs[0][0])\n        finally:\n            if not connection.closed:\n                terminal.close()\n\n\n# Exercise every pattern-backed state through the real terminal, driver, and\n# commander. States that represent a login transition include the follow-up\n# prompt needed for the real scheduler to safely finish the feature.\nSTATE_CASES = [\n    (\"username_prompt\", FOSCliState.PROVIDE_USERNAME, b\"fw login:\\r\\n\", b\"Password:\\r\\nWelcome!\\r\\nfw #\\r\\n\", False),\n    (\"password_prompt\", FOSCliState.PROVIDE_PASSWORD, b\"Password:\", b\"\", False),\n    (\"new_password_prompt\", FOSCliState.CHANGE_PASSWORD, b\"New Password:\", b\"\", False),\n    (\"credential_rejected\", FOSCliState.CREDENTIAL_REJECTED, b\"Login incorrect\\r\\n\", b\"fw login:\\r\\nPassword:\\r\\nWelcome!\\r\\nfw #\\r\\n\", True),\n    (\"credential_accepted\", FOSCliState.CREDENTIAL_ACCEPTED, b\"Welcome!\\r\\n\", b\"fw #\\r\\n\", False),\n    (\"license_failure_notice\", FOSCliState.LIC_FAIL, b\"VM license install failed.\\r\\n\", b\"\", False),\n    (\"command_prompt\", FOSCliState.CMD_PROMPT, b\"fw #\\r\\n\", b\"\", False),\n    (\"command_prompt_echo\", FOSCliState.CMD_PROMPT_ECHO, b\"fw (global) # probe\\r\\n\", b\"fw (global) #\\r\\n\", False),\n    (\"shutdown_notice\", FOSCliState.SHUTTING_DOWN, b\"system is going down\\r\\n\", b\"\", False),\n    (\"reboot_notice\", FOSCliState.REBOOTING, b\"stand by while rebooting\\r\\n\", b\"\", False),\n    (\"session_lost_notice\", FOSCliState.SESSION_LOST, b\"*ATTENTION*: Admin sessions removed because license registration status changed\\r\\n\", b\"Welcome!\\r\\nfw #\\r\\n\", False),\n    (\"current_password_prompt\", FOSCliState.CURRENT_PASSWORD, b\"Current Password:\\r\\n\", b\"\", False),\n    (\"confirmation_prompt\", FOSCliState.CONFIRMATION, b\"Do you want to continue?\\r\\n\", b\"\", False),\n    (\"confirm_new_password_prompt\", FOSCliState.CHANGE_PASSWORD_CONFIRM, b\"Confirm Password:\\r\\n\", b\"\", False),\n    (\"pager_prompt\", FOSCliState.MORE_PROMPT, b\"--More--\", b\"\", False),\n    (\"multiline_prompt\", FOSCliState.MULTILINE_PROMPT, b\">\\r\\n\", b\"\", False),\n]\n\n\ndef _make_state_test(case):\n    name, state, sample, suffix, recover = case\n    def test(self):\n        with self.subTest(state=state.name):\n            state_case(state, sample, suffix, recover=recover)\n    test.__name__ = f\"test_state_{name}_through_full_stack\"\n    test.__doc__ = f\"Reach {state.name} from connection bytes and observe commander handling.\"\n    return test\n\n\nfor _case in STATE_CASES:\n    setattr(EndToEndBoundaryCases, f\"test_state_{_case[0]}_through_full_stack\", _make_state_test(_case))\n\n\n# Hostname, prompt context, prompt glyph, and line ending are independent\n# parser boundaries. The Cartesian set creates one discoverable test per wire\n# shape so failures point to the exact prompt form.\nPROMPT_CASES = [\n    (host, context, marker, ending)\n    for host in (\"fw\", \"edge-01\", \"FortiGate-VM64-KVM\", \"FGVMABC123\")\n    for context in (\"\", \" (global)\", \" (root) (vdom blue)\")\n    for marker in (\"#\", \"$\")\n    for ending in (\"\\n\", \"\\r\\n\")\n]\n\n\ndef _make_prompt_test(case):\n    hostname, context, marker, ending = case\n    label = f\"{hostname}_{context or 'plain'}_{marker}_{'crlf' if ending == chr(13)+chr(10) else 'lf'}\"\n    def test(self):\n        prompt_case(hostname, context, marker, ending)\n    test.__name__ = \"test_prompt_\" + \"_\".join(part.replace(\" \", \"\").replace(\"(\", \"\").replace(\")\", \"\") for part in label.split(\"_\"))\n    test.__doc__ = f\"Parse command echo and prompt {hostname}{context} {marker} with {ending!r}.\"\n    return test\n\n\nfor _case in PROMPT_CASES:\n    setattr(EndToEndBoundaryCases, _make_prompt_test(_case).__name__, _make_prompt_test(_case))\n\n\n# Distinct failure payloads ensure the command failure parser handles signed\n# and unsigned return codes and optional whitespace over the serial boundary.\nERROR_CASES = [b\"0\", b\"1\", b\"-1\", b\"-5\", b\"-542\", b\"255\", b\"0007\", b\"-214\"]\n\n\ndef _make_failure_test(return_code):\n    def test(self):\n        response = b\"Command fail. Return code \" + return_code + b\"\\r\\nfw #\\r\\n\"\n        connection, terminal, _commander, driver, _feature, _states = make_stack(\n            CommandSpec(\"probe\", capture_output=True, fail_on_error=True), response\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                with self.assertRaisesRegex(RuntimeError, f\"return code {return_code.decode()}\"):\n                    driver.process_state()\n        finally:\n            terminal.close()\n    test.__name__ = f\"test_command_error_code_{return_code.decode().replace('-', 'negative_')}\"\n    test.__doc__ = f\"Pass FortiOS return code {return_code.decode()} through the full stack.\"\n    return test\n\n\nfor _code in ERROR_CASES:\n    setattr(EndToEndBoundaryCases, _make_failure_test(_code).__name__, _make_failure_test(_code))\n\n\nCAPTURE_CASES = [\n    b\"one line\\n\",\n    b\"multiple\\nlines\\nwith trailing newline\\n\",\n    b\"carriage return\\rwithout line feed\",\n    b\"\\xff\\xfe\\x00binary-ish bytes\",\n    b\"\\x1b[31mcolored output\\x1b[0m\",\n    b\"tabs\\tand    repeated spaces\",\n    b\"# metadata-looking output\",\n    b\"prompt-like value fw (global) # inside data\",\n    b\"empty-looking\\n\\nline\",\n    b\"unicode utf-8: \\xe2\\x98\\x83\",\n    b\"long\" * 2048,\n    b\"return code text: Command fail. Return code -7\",\n]\n\n\ndef _make_capture_test(index, payload):\n    def test(self):\n        ending = b\"\\r\\n\"\n        response = payload + ending + b\"fw #\\r\\n\"\n        connection, terminal, commander, driver, feature, _states = make_stack(\n            CommandSpec(\"probe\", capture_output=True), response\n        )\n        try:\n            with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                    patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                driver.process_state()\n            self.assertTrue(commander.ready)\n            self.assertEqual(feature.outputs[0][1], FOSCliState.CMD_PROMPT)\n            self.assertIn(payload, feature.outputs[0][0])\n        finally:\n            if not connection.closed:\n                terminal.close()\n    test.__name__ = f\"test_capture_payload_{index:02d}\"\n    test.__doc__ = f\"Capture serial output payload case {index}.\"\n    return test\n\n\nfor _index, _payload in enumerate(CAPTURE_CASES):\n    setattr(EndToEndBoundaryCases, f\"test_capture_payload_{_index:02d}\", _make_capture_test(_index, _payload))\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 349,
        "totalLines": 349,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716555559,
      "end": 1793716555564
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_stack_parsing.py"
}

Output

<path>/source/head/fortinet/tests/test_common_stack_parsing.py</path>
<type>file</type>
<content>
1: """End-to-end parsing from a serial connection through the FortiOS commander."""
2: 
3: import queue
4: import sys
5: import unittest
6: from pathlib import Path
7: from unittest.mock import MagicMock
8: 
9: REPO_ROOT = Path(__file__).resolve().parents[2]
10: sys.path.insert(0, str(REPO_ROOT))
11: 
12: from fortinet.common.cli_commands import (  # noqa: E402
13:     CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,
14: )
15: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
16: from fortinet.common.features.base import Feature  # noqa: E402
17: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
18: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
19: from fortinet.common.terminal import Terminal  # noqa: E402
20: 
21: 
22: class SerialConnection:
23:     """A serial-like connection that answers each write with a byte stream."""
24: 
25:     def __init__(self, responses):
26:         self._incoming = queue.Queue()
27:         self._responses = responses
28:         self.writes = []
29:         self.closed = False
30:         self._incoming.put(b"fw login:\r\n")
31: 
32:     def read_very_eager(self):
33:         try:
34:             return self._incoming.get_nowait()
35:         except queue.Empty:
36:             return b""
37: 
38:     def write(self, data):
39:         data = bytes(data)
40:         self.writes.append(data)
41:         response = self._responses.get(data)
42:         if callable(response):
43:             response = response()
44:         if response:
45:             chunks = response if isinstance(response, (tuple, list)) else (response,)
46:             for chunk in chunks:
47:                 if chunk:
48:                     self._incoming.put(bytes(chunk))
49: 
50:     def close(self):
51:         self.closed = True
52: 
53:     def suppress_output(self):
54:         from contextlib import nullcontext
55:         return nullcontext()
56: 
57: 
58: class RecordingFeature(Feature):
59:     def __init__(self, commander, name, commands):
60:         super().__init__(None, commander, name)
61:         self.commands = commands
62:         self.executed = []
63:         self.dispatched = []
64: 
65:     def activate(self):
66:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))
67: 
68:     def on_command_dispatched(self, attempt):
69:         super().on_command_dispatched(attempt)
70:         self.dispatched.append(attempt)
71: 
72:     def on_command_executed(self, attempt, state):
73:         self.executed.append((attempt.spec.line, bytes(attempt.output), state))
74: 
75: 
76: class FullStackParsingTests(unittest.TestCase):
77:     def make_stack(self, features, responses, *, allow_credential_recovery=False):
78:         logger = MagicMock()
79:         connection = SerialConnection(responses)
80:         terminal = Terminal(connection, logger, default_wait="fw #")
81:         commander = FOSCommander(terminal, logger)
82:         commander.start(features(commander))
83:         driver = FOSCliDriver(
84:             terminal=terminal,
85:             commander=commander,
86:             credentials=Credentials("admin", "secret"),
87:             logger=logger,
88:             bootstrap_password="Bootstrap1!",
89:             activate_blank_credentials=MagicMock(),
90:             activate_bootstrap_credentials=MagicMock(),
91:             allow_credential_recovery=allow_credential_recovery,
92:         )
93:         return connection, terminal, commander, driver
94: 
95:     def test_login_command_echo_multiline_output_and_continuation(self):
96:         result = b"".join([
97:             b"fw # show full-configuration system dns\r\n",
98:             b"config system dns\r\n",
99:             b"    set protocol dot\r\n",
100:             b"    set primary 9.9.9.9\r\n",
101:             b"end\r\n",
102:             b"fw #\r\n",
103:         ])
104:         responses = {
105:             b"admin\r": b"Password:",
106:             b"secret\r": b"Welcome!\r\nfw #\r\n",
107:             b"show full-configuration system dns\r": result,
108:             b'set comment "first line\r': b">\r\n",
109:             b"second line\r": b">\r\n",
110:             b'third line"\r': b"fw #\r\n",
111:         }
112:         features = []
113: 
114:         def configured(commander):
115:             inspect = RecordingFeature(commander, "inspect", [
116:                 CommandSpec("show full-configuration system dns", capture_output=True),
117:             ])
118:             multiline = RecordingFeature(commander, "multiline", [
119:                 SetValue("comment", "first line\nsecond line\nthird line"),
120:             ])
121:             features.extend([inspect, multiline])
122:             return features
123: 
124:         connection, terminal, commander, driver = self.make_stack(configured, responses)
125:         driver.process_state()
126: 
127:         self.assertTrue(commander.ready)
128:         self.assertTrue(commander.startup_complete)
129:         self.assertTrue(all(feature.completed for feature in features))
130:         self.assertTrue(connection.closed)
131:         self.assertEqual(connection.writes, [
132:             b"admin\r",
133:             b"secret\r",
134:             b"show full-configuration system dns\r",
135:             b'set comment "first line\r',
136:             b"second line\r",
137:             b'third line"\r',
138:         ])
139:         self.assertEqual(len(features[0].executed), 1)
140:         captured = features[0].executed[0][1]
141:         self.assertIn(b"set protocol dot", captured)
142:         self.assertIn(b"set primary 9.9.9.9", captured)
143:         self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)
144:         self.assertEqual(
145:             [entry[2] for entry in features[1].executed],
146:             [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],
147:         )
148:         self.assertTrue(all(attempt.output for attempt in features[1].dispatched))
149:         self.assertEqual(bytes(terminal._buffer), b"")
150: 
151:     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):
152:         responses = {
153:             b"admin\r": b"Password:",
154:             b"secret\r": b"Welcome!\r\nfw (global) #\r\n",
155:             b"get system status\r": (
156:                 b"fw (global) # get system status\r\n"
157:                 b"Version: FortiGate-VM64 v7.4.2,build2571\r\n"
158:                 b"--More--\r\n"
159:                 b"Serial-Number: FGVMTEST\r\n"
160:                 b"fw (global) #\r\n"
161:             ),
162:             b" \r": b"fw (global) #\r\n",
163:         }
164:         feature_ref = []
165: 
166:         class PagerFeature(RecordingFeature):
167:             def on_command_executed(self, attempt, state):
168:                 super().on_command_executed(attempt, state)
169:                 self.commander.feature_complete(self)
170: 
171:         def configured(commander):
172:             feature = PagerFeature(commander, "status", [
173:                 CommandSpec("get system status", capture_output=True),
174:             ])
175:             feature_ref.append(feature)
176:             return [feature]
177: 
178:         connection, _terminal, commander, driver = self.make_stack(configured, responses)
179:         driver.process_state()
180: 
181:         feature = feature_ref[0]
182:         self.assertTrue(commander.ready)
183:         self.assertTrue(feature.completed)
184:         self.assertEqual(connection.writes, [
185:             b"admin\r", b"secret\r", b"get system status\r", b" ",
186:         ])
187:         captured = feature.executed[0][1]
188:         self.assertIn(b"FortiGate-VM64 v7.4.2,build2571", captured)
189:         self.assertIn(b"Serial-Number: FGVMTEST", captured)
190:         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)
191:         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)
192: 
193:     def test_aborted_interface_edit_recovers_through_serial_driver(self):
194:         ip_responses = iter([
195:             b"abort\r\nfw (Interim)#\r\n",
196:             b"fw (port1) (Interim)#\r\n",
197:         ])
198:         responses = {
199:             b"admin\r": b"Password:",
200:             b"secret\r": b"Welcome!\r\nfw (Interim)#\r\n",
201:             b"config system interface\r": b"fw (interface) (Interim)#\r\n",
202:             b"edit port1\r": b"fw (port1) (Interim)#\r\n",
203:             b"set ip 10.0.52.4/24\r": lambda: next(ip_responses),
204:             b"set allowaccess ping https ssh http\r": b"fw (port1) (Interim)#\r\n",
205:             b"next\r": b"fw (interface) (Interim)#\r\n",
206:             b"end\r": b"fw (Interim)#\r\n",
207:         }
208:         feature_ref = []
209: 
210:         def configured(commander):
211:             feature = RecordingFeature(commander, "management", [
212:                 ConfigBlock("system interface", [EditBlock("port1", [
213:                     "set ip 10.0.52.4/24", "set allowaccess ping https ssh http",
214:                 ])]),
215:             ])
216:             feature_ref.append(feature)
217:             return [feature]
218: 
219:         connection, terminal, commander, driver = self.make_stack(configured, responses)
220:         try:
221:             driver.process_state()
222:             self.assertTrue(commander.ready)
223:             self.assertTrue(feature_ref[0].completed)
224:             self.assertEqual(connection.writes, [
225:                 b"admin\r", b"secret\r",
226:                 b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
227:                 b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
228:                 b"set allowaccess ping https ssh http\r", b"next\r", b"end\r",
229:             ])
230:         finally:
231:             terminal.close()
232: 
233:     def test_failed_next_ejects_before_end_through_serial_driver(self):
234:         responses = {
235:             b"admin\r": b"Password:",
236:             b"secret\r": b"Welcome!\r\nfw #\r\n",
237:             b"config system interface\r": b"fw (interface)#\r\n",
238:             b"edit port1\r": b"fw (port1)#\r\n",
239:             b"set unsupported 1\r": b"Command fail. Return code -61.\r\nfw (port1)#\r\n",
240:             b"next\r": (
241:                 b"Command fa", b"il. Return code -5.\r\nfw (port1)#\r\n",
242:             ),
243:         }
244:         feature_ref = []
245: 
246:         def configured(commander):
247:             feature = RecordingFeature(commander, "management", [
248:                 ConfigBlock("system interface", [EditBlock("port1", ["set unsupported 1"])]),
249:             ])
250:             feature_ref.append(feature)
251:             return [feature]
252: 
253:         connection, terminal, commander, driver = self.make_stack(configured, responses)
254:         try:
255:             with self.assertRaisesRegex(RuntimeError, "'next'.*return code -5"):
256:                 driver.process_state()
257:             self.assertEqual(connection.writes, [
258:                 b"admin\r", b"secret\r", b"config system interface\r",
259:                 b"edit port1\r", b"set unsupported 1\r", b"next\r",
260:             ])
261:             self.assertFalse(feature_ref[0].completed)
262:             self.assertFalse(commander.ready)
263:         finally:
264:             terminal.close()
265: 
266: 
267: if __name__ == "__main__":
268:     unittest.main()

(End of file - total 268 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d68f67001UPURhbDkwPgVzz",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d67f02001f8lG7xsSMGR7pA",
  "callID": "call_16d829bb6a8f43158c0eec04",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_stack_parsing.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_stack_parsing.py</path>\n<type>file</type>\n<content>\n1: \"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n2: \n3: import queue\n4: import sys\n5: import unittest\n6: from pathlib import Path\n7: from unittest.mock import MagicMock\n8: \n9: REPO_ROOT = Path(__file__).resolve().parents[2]\n10: sys.path.insert(0, str(REPO_ROOT))\n11: \n12: from fortinet.common.cli_commands import (  # noqa: E402\n13:     CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n14: )\n15: from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n16: from fortinet.common.features.base import Feature  # noqa: E402\n17: from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n18: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n19: from fortinet.common.terminal import Terminal  # noqa: E402\n20: \n21: \n22: class SerialConnection:\n23:     \"\"\"A serial-like connection that answers each write with a byte stream.\"\"\"\n24: \n25:     def __init__(self, responses):\n26:         self._incoming = queue.Queue()\n27:         self._responses = responses\n28:         self.writes = []\n29:         self.closed = False\n30:         self._incoming.put(b\"fw login:\\r\\n\")\n31: \n32:     def read_very_eager(self):\n33:         try:\n34:             return self._incoming.get_nowait()\n35:         except queue.Empty:\n36:             return b\"\"\n37: \n38:     def write(self, data):\n39:         data = bytes(data)\n40:         self.writes.append(data)\n41:         response = self._responses.get(data)\n42:         if callable(response):\n43:             response = response()\n44:         if response:\n45:             chunks = response if isinstance(response, (tuple, list)) else (response,)\n46:             for chunk in chunks:\n47:                 if chunk:\n48:                     self._incoming.put(bytes(chunk))\n49: \n50:     def close(self):\n51:         self.closed = True\n52: \n53:     def suppress_output(self):\n54:         from contextlib import nullcontext\n55:         return nullcontext()\n56: \n57: \n58: class RecordingFeature(Feature):\n59:     def __init__(self, commander, name, commands):\n60:         super().__init__(None, commander, name)\n61:         self.commands = commands\n62:         self.executed = []\n63:         self.dispatched = []\n64: \n65:     def activate(self):\n66:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n67: \n68:     def on_command_dispatched(self, attempt):\n69:         super().on_command_dispatched(attempt)\n70:         self.dispatched.append(attempt)\n71: \n72:     def on_command_executed(self, attempt, state):\n73:         self.executed.append((attempt.spec.line, bytes(attempt.output), state))\n74: \n75: \n76: class FullStackParsingTests(unittest.TestCase):\n77:     def make_stack(self, features, responses, *, allow_credential_recovery=False):\n78:         logger = MagicMock()\n79:         connection = SerialConnection(responses)\n80:         terminal = Terminal(connection, logger, default_wait=\"fw #\")\n81:         commander = FOSCommander(terminal, logger)\n82:         commander.start(features(commander))\n83:         driver = FOSCliDriver(\n84:             terminal=terminal,\n85:             commander=commander,\n86:             credentials=Credentials(\"admin\", \"secret\"),\n87:             logger=logger,\n88:             bootstrap_password=\"Bootstrap1!\",\n89:             activate_blank_credentials=MagicMock(),\n90:             activate_bootstrap_credentials=MagicMock(),\n91:             allow_credential_recovery=allow_credential_recovery,\n92:         )\n93:         return connection, terminal, commander, driver\n94: \n95:     def test_login_command_echo_multiline_output_and_continuation(self):\n96:         result = b\"\".join([\n97:             b\"fw # show full-configuration system dns\\r\\n\",\n98:             b\"config system dns\\r\\n\",\n99:             b\"    set protocol dot\\r\\n\",\n100:             b\"    set primary 9.9.9.9\\r\\n\",\n101:             b\"end\\r\\n\",\n102:             b\"fw #\\r\\n\",\n103:         ])\n104:         responses = {\n105:             b\"admin\\r\": b\"Password:\",\n106:             b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n107:             b\"show full-configuration system dns\\r\": result,\n108:             b'set comment \"first line\\r': b\">\\r\\n\",\n109:             b\"second line\\r\": b\">\\r\\n\",\n110:             b'third line\"\\r': b\"fw #\\r\\n\",\n111:         }\n112:         features = []\n113: \n114:         def configured(commander):\n115:             inspect = RecordingFeature(commander, \"inspect\", [\n116:                 CommandSpec(\"show full-configuration system dns\", capture_output=True),\n117:             ])\n118:             multiline = RecordingFeature(commander, \"multiline\", [\n119:                 SetValue(\"comment\", \"first line\\nsecond line\\nthird line\"),\n120:             ])\n121:             features.extend([inspect, multiline])\n122:             return features\n123: \n124:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n125:         driver.process_state()\n126: \n127:         self.assertTrue(commander.ready)\n128:         self.assertTrue(commander.startup_complete)\n129:         self.assertTrue(all(feature.completed for feature in features))\n130:         self.assertTrue(connection.closed)\n131:         self.assertEqual(connection.writes, [\n132:             b\"admin\\r\",\n133:             b\"secret\\r\",\n134:             b\"show full-configuration system dns\\r\",\n135:             b'set comment \"first line\\r',\n136:             b\"second line\\r\",\n137:             b'third line\"\\r',\n138:         ])\n139:         self.assertEqual(len(features[0].executed), 1)\n140:         captured = features[0].executed[0][1]\n141:         self.assertIn(b\"set protocol dot\", captured)\n142:         self.assertIn(b\"set primary 9.9.9.9\", captured)\n143:         self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)\n144:         self.assertEqual(\n145:             [entry[2] for entry in features[1].executed],\n146:             [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],\n147:         )\n148:         self.assertTrue(all(attempt.output for attempt in features[1].dispatched))\n149:         self.assertEqual(bytes(terminal._buffer), b\"\")\n150: \n151:     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n152:         responses = {\n153:             b\"admin\\r\": b\"Password:\",\n154:             b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n155:             b\"get system status\\r\": (\n156:                 b\"fw (global) # get system status\\r\\n\"\n157:                 b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n158:                 b\"--More--\\r\\n\"\n159:                 b\"Serial-Number: FGVMTEST\\r\\n\"\n160:                 b\"fw (global) #\\r\\n\"\n161:             ),\n162:             b\" \\r\": b\"fw (global) #\\r\\n\",\n163:         }\n164:         feature_ref = []\n165: \n166:         class PagerFeature(RecordingFeature):\n167:             def on_command_executed(self, attempt, state):\n168:                 super().on_command_executed(attempt, state)\n169:                 self.commander.feature_complete(self)\n170: \n171:         def configured(commander):\n172:             feature = PagerFeature(commander, \"status\", [\n173:                 CommandSpec(\"get system status\", capture_output=True),\n174:             ])\n175:             feature_ref.append(feature)\n176:             return [feature]\n177: \n178:         connection, _terminal, commander, driver = self.make_stack(configured, responses)\n179:         driver.process_state()\n180: \n181:         feature = feature_ref[0]\n182:         self.assertTrue(commander.ready)\n183:         self.assertTrue(feature.completed)\n184:         self.assertEqual(connection.writes, [\n185:             b\"admin\\r\", b\"secret\\r\", b\"get system status\\r\", b\" \",\n186:         ])\n187:         captured = feature.executed[0][1]\n188:         self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n189:         self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n190:         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n191:         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n192: \n193:     def test_aborted_interface_edit_recovers_through_serial_driver(self):\n194:         ip_responses = iter([\n195:             b\"abort\\r\\nfw (Interim)#\\r\\n\",\n196:             b\"fw (port1) (Interim)#\\r\\n\",\n197:         ])\n198:         responses = {\n199:             b\"admin\\r\": b\"Password:\",\n200:             b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n201:             b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n202:             b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n203:             b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n204:             b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n205:             b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n206:             b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n207:         }\n208:         feature_ref = []\n209: \n210:         def configured(commander):\n211:             feature = RecordingFeature(commander, \"management\", [\n212:                 ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n213:                     \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n214:                 ])]),\n215:             ])\n216:             feature_ref.append(feature)\n217:             return [feature]\n218: \n219:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n220:         try:\n221:             driver.process_state()\n222:             self.assertTrue(commander.ready)\n223:             self.assertTrue(feature_ref[0].completed)\n224:             self.assertEqual(connection.writes, [\n225:                 b\"admin\\r\", b\"secret\\r\",\n226:                 b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n227:                 b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n228:                 b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n229:             ])\n230:         finally:\n231:             terminal.close()\n232: \n233:     def test_failed_next_ejects_before_end_through_serial_driver(self):\n234:         responses = {\n235:             b\"admin\\r\": b\"Password:\",\n236:             b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n237:             b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n238:             b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n239:             b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n240:             b\"next\\r\": (\n241:                 b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n242:             ),\n243:         }\n244:         feature_ref = []\n245: \n246:         def configured(commander):\n247:             feature = RecordingFeature(commander, \"management\", [\n248:                 ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n249:             ])\n250:             feature_ref.append(feature)\n251:             return [feature]\n252: \n253:         connection, terminal, commander, driver = self.make_stack(configured, responses)\n254:         try:\n255:             with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n256:                 driver.process_state()\n257:             self.assertEqual(connection.writes, [\n258:                 b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n259:                 b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n260:             ])\n261:             self.assertFalse(feature_ref[0].completed)\n262:             self.assertFalse(commander.ready)\n263:         finally:\n264:             terminal.close()\n265: \n266: \n267: if __name__ == \"__main__\":\n268:     unittest.main()\n\n(End of file - total 268 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_stack_parsing.py",
    "metadata": {
      "preview": "\"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n\nimport queue\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n)\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_stack_parsing.py",
        "text": "\"\"\"End-to-end parsing from a serial connection through the FortiOS commander.\"\"\"\n\nimport queue\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nREPO_ROOT = Path(__file__).resolve().parents[2]\nsys.path.insert(0, str(REPO_ROOT))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n)\nfrom fortinet.common.common import Credentials, FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Terminal  # noqa: E402\n\n\nclass SerialConnection:\n    \"\"\"A serial-like connection that answers each write with a byte stream.\"\"\"\n\n    def __init__(self, responses):\n        self._incoming = queue.Queue()\n        self._responses = responses\n        self.writes = []\n        self.closed = False\n        self._incoming.put(b\"fw login:\\r\\n\")\n\n    def read_very_eager(self):\n        try:\n            return self._incoming.get_nowait()\n        except queue.Empty:\n            return b\"\"\n\n    def write(self, data):\n        data = bytes(data)\n        self.writes.append(data)\n        response = self._responses.get(data)\n        if callable(response):\n            response = response()\n        if response:\n            chunks = response if isinstance(response, (tuple, list)) else (response,)\n            for chunk in chunks:\n                if chunk:\n                    self._incoming.put(bytes(chunk))\n\n    def close(self):\n        self.closed = True\n\n    def suppress_output(self):\n        from contextlib import nullcontext\n        return nullcontext()\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):\n        super().__init__(None, commander, name)\n        self.commands = commands\n        self.executed = []\n        self.dispatched = []\n\n    def activate(self):\n        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n\n    def on_command_dispatched(self, attempt):\n        super().on_command_dispatched(attempt)\n        self.dispatched.append(attempt)\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append((attempt.spec.line, bytes(attempt.output), state))\n\n\nclass FullStackParsingTests(unittest.TestCase):\n    def make_stack(self, features, responses, *, allow_credential_recovery=False):\n        logger = MagicMock()\n        connection = SerialConnection(responses)\n        terminal = Terminal(connection, logger, default_wait=\"fw #\")\n        commander = FOSCommander(terminal, logger)\n        commander.start(features(commander))\n        driver = FOSCliDriver(\n            terminal=terminal,\n            commander=commander,\n            credentials=Credentials(\"admin\", \"secret\"),\n            logger=logger,\n            bootstrap_password=\"Bootstrap1!\",\n            activate_blank_credentials=MagicMock(),\n            activate_bootstrap_credentials=MagicMock(),\n            allow_credential_recovery=allow_credential_recovery,\n        )\n        return connection, terminal, commander, driver\n\n    def test_login_command_echo_multiline_output_and_continuation(self):\n        result = b\"\".join([\n            b\"fw # show full-configuration system dns\\r\\n\",\n            b\"config system dns\\r\\n\",\n            b\"    set protocol dot\\r\\n\",\n            b\"    set primary 9.9.9.9\\r\\n\",\n            b\"end\\r\\n\",\n            b\"fw #\\r\\n\",\n        ])\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n            b\"show full-configuration system dns\\r\": result,\n            b'set comment \"first line\\r': b\">\\r\\n\",\n            b\"second line\\r\": b\">\\r\\n\",\n            b'third line\"\\r': b\"fw #\\r\\n\",\n        }\n        features = []\n\n        def configured(commander):\n            inspect = RecordingFeature(commander, \"inspect\", [\n                CommandSpec(\"show full-configuration system dns\", capture_output=True),\n            ])\n            multiline = RecordingFeature(commander, \"multiline\", [\n                SetValue(\"comment\", \"first line\\nsecond line\\nthird line\"),\n            ])\n            features.extend([inspect, multiline])\n            return features\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        driver.process_state()\n\n        self.assertTrue(commander.ready)\n        self.assertTrue(commander.startup_complete)\n        self.assertTrue(all(feature.completed for feature in features))\n        self.assertTrue(connection.closed)\n        self.assertEqual(connection.writes, [\n            b\"admin\\r\",\n            b\"secret\\r\",\n            b\"show full-configuration system dns\\r\",\n            b'set comment \"first line\\r',\n            b\"second line\\r\",\n            b'third line\"\\r',\n        ])\n        self.assertEqual(len(features[0].executed), 1)\n        captured = features[0].executed[0][1]\n        self.assertIn(b\"set protocol dot\", captured)\n        self.assertIn(b\"set primary 9.9.9.9\", captured)\n        self.assertEqual(features[0].executed[0][2], FOSCliState.CMD_PROMPT)\n        self.assertEqual(\n            [entry[2] for entry in features[1].executed],\n            [FOSCliState.MULTILINE_PROMPT, FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT],\n        )\n        self.assertTrue(all(attempt.output for attempt in features[1].dispatched))\n        self.assertEqual(bytes(terminal._buffer), b\"\")\n\n    def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n            b\"get system status\\r\": (\n                b\"fw (global) # get system status\\r\\n\"\n                b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n                b\"--More--\\r\\n\"\n                b\"Serial-Number: FGVMTEST\\r\\n\"\n                b\"fw (global) #\\r\\n\"\n            ),\n            b\" \\r\": b\"fw (global) #\\r\\n\",\n        }\n        feature_ref = []\n\n        class PagerFeature(RecordingFeature):\n            def on_command_executed(self, attempt, state):\n                super().on_command_executed(attempt, state)\n                self.commander.feature_complete(self)\n\n        def configured(commander):\n            feature = PagerFeature(commander, \"status\", [\n                CommandSpec(\"get system status\", capture_output=True),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, _terminal, commander, driver = self.make_stack(configured, responses)\n        driver.process_state()\n\n        feature = feature_ref[0]\n        self.assertTrue(commander.ready)\n        self.assertTrue(feature.completed)\n        self.assertEqual(connection.writes, [\n            b\"admin\\r\", b\"secret\\r\", b\"get system status\\r\", b\" \",\n        ])\n        captured = feature.executed[0][1]\n        self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n        self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n        self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n        self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n\n    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n        ip_responses = iter([\n            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n            b\"fw (port1) (Interim)#\\r\\n\",\n        ])\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n        }\n        feature_ref = []\n\n        def configured(commander):\n            feature = RecordingFeature(commander, \"management\", [\n                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n                ])]),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        try:\n            driver.process_state()\n            self.assertTrue(commander.ready)\n            self.assertTrue(feature_ref[0].completed)\n            self.assertEqual(connection.writes, [\n                b\"admin\\r\", b\"secret\\r\",\n                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n            ])\n        finally:\n            terminal.close()\n\n    def test_failed_next_ejects_before_end_through_serial_driver(self):\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n            b\"next\\r\": (\n                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n            ),\n        }\n        feature_ref = []\n\n        def configured(commander):\n            feature = RecordingFeature(commander, \"management\", [\n                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n            ])\n            feature_ref.append(feature)\n            return [feature]\n\n        connection, terminal, commander, driver = self.make_stack(configured, responses)\n        try:\n            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n                driver.process_state()\n            self.assertEqual(connection.writes, [\n                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n            ])\n            self.assertFalse(feature_ref[0].completed)\n            self.assertFalse(commander.ready)\n        finally:\n            terminal.close()\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 268,
        "totalLines": 268,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716555626,
      "end": 1793716555630
    }
  }
}
read · error

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_terminal_driver.py",
  "offset": 600
}

Output

Offset 600 is out of range for this file (332 lines)
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d68fad0012UB0E9wiS680fM",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d67f02001f8lG7xsSMGR7pA",
  "callID": "call_25a59c630b6944c785818c6d",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_terminal_driver.py",
      "offset": 600
    },
    "error": "Offset 600 is out of range for this file (332 lines)",
    "time": {
      "start": 1793716555696,
      "end": 1793716555703
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d68fba00161eXdcEJRxMQFe",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d67f02001f8lG7xsSMGR7pA",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 32123,
    "input": 9270,
    "output": 74,
    "reasoning": 251,
    "cache": {
      "read": 22528,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d67f02001f8lG7xsSMGR7pA",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716551426,
    "completed": 1793716555710
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 32123,
    "input": 9270,
    "output": 74,
    "reasoning": 251,
    "cache": {
      "read": 22528,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 28
step-start
{
  "type": "step-start",
  "id": "prt_1a1d6976a001USnegI3bKc4hD7",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d68fc6001YUuZT3OH6uecsd"
}
Reasoning
test_common_terminal_driver.py is 332 lines? Earlier I read the first 600 lines... wait, that means the whole file was read (332 lines). Hmm, the earlier summary said "truncated at 600 lines" — maybe it was 600+ lines but now 332? No — the earlier read reported the first ~600 lines of test_common_terminal_driver.py, but now file total is 332 lines. That's contradictory. Maybe earlier read was actually of a different path? The prior summary may be inaccurate. Actually the offset 600 out-of-range with 332 lines means the file is 332 lines and I've effectively read it all already (I read lines 1-332 earlier). Fine.

Wait — but the earlier summary said test_common_terminal_driver.py first 600 lines truncated. Whatever; the file is 332 lines, so fully covered.

Hmm, but wait: STATE_CASES in test_common_stack_boundaries.py references FOSCliState.MULTILINE_PROMPT, CONFIRMATION, SHUTTING_DOWN, REBOOTING, SESSION_LOST, MORE_PROMPT etc. — these must exist in common.py. I read common.py (92 lines total per this read... wait, earlier summary said common.py first 120 lines read with TRACE_LEVEL=9 etc. Now offset 120 is out of range (92 lines). So common.py is 92 lines — fully read.

Hmm, but hold on: is common.py really only 92 lines with all those states? FOSCliState enum with ~18 states plus regexes in 92 lines — plausible with compact formatting.

Now remaining reads:
- test_common_terminal_driver.py — need to verify I've seen all 332 lines. I previously read "first 600 lines" per summary — but the file is 332 lines, so I've seen it all. OK.
- test_common_admin_credentials.py, test_common_recovery.py, test_common_scope_errors.py — earlier reads were "truncated". Need to check their sizes and read remainder.
- READMEs: fortigate/README.md, fortigate/docker/README.md.
- Also need to double check fos_commander.py fully read (687 lines) — yes.

Let me read the three new test files fully and the READMEs. I'll batch.
The parsing and boundaries tests are fully read. Now the three new test files and the two READMEs.
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_admin_credentials.py"
}

Output

<path>/source/head/fortinet/tests/test_common_admin_credentials.py</path>
<type>file</type>
<content>
1: """Admin credential commits followed by logout and console authentication."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from types import SimpleNamespace
7: from unittest.mock import MagicMock, patch
8: 
9: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
10: 
11: from fortinet.common.common import Credentials
12: from fortinet.common.features.credentials import CredentialsFeature
13: from fortinet.common.fos_cli_driver import FOSCliDriver
14: from fortinet.common.fos_commander import FOSCommander
15: from fortinet.common.terminal import Terminal
16: from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection
17: 
18: 
19: LOGIN = b"fw login:\r\n"
20: READY = b"Welcome!\r\nfw #\r\n"
21: ADMIN_PROMPT = b"fw (admin) #\r\n"
22: 
23: 
24: class AdminCredentialsTests(unittest.TestCase):
25:     def make_stack(self, *, password="newpass", username="admin",
26:                    auto_logout=None, authenticate=True, reject=False,
27:                    exit_works=True):
28:         logger = MagicMock()
29:         policy_prompt = b"fw (password-policy) #\r\n"
30:         old_password_responses = [READY]
31:         if password:
32:             old_password_responses.append(ADMIN_PROMPT)
33:         old_password_responses.append(b"Login incorrect\r\n" + LOGIN)
34:         end_count = 0
35: 
36:         def end_response():
37:             nonlocal end_count
38:             end_count += 1
39:             return LOGIN if auto_logout == "end" and end_count == 2 else b"fw #\r\n"
40: 
41:         login_reply = None if not authenticate else (
42:             b"Login incorrect\r\n" + LOGIN if reject else READY
43:         )
44:         responses = {
45:             b"admin\r": b"Password:",
46:             b"oldpass\r": lambda: old_password_responses.pop(0),
47:             b"config system password-policy\r": policy_prompt,
48:             b"set status disable\r": policy_prompt,
49:             b"config system admin\r": ADMIN_PROMPT,
50:             f"edit {username}\r".encode(): ADMIN_PROMPT,
51:             b"set accprofile super_admin\r": ADMIN_PROMPT,
52:             b"next\r": LOGIN if auto_logout == "next" else ADMIN_PROMPT,
53:             b"end\r": end_response,
54:             b"exit\r": LOGIN if exit_works else b"fw #\r\n",
55:             b"probe\r": b"fw #\r\n",
56:             (password + "\r").encode(): login_reply,
57:         }
58:         if username != "admin":
59:             responses[(username + "\r").encode()] = b"Password:"
60:         if password:
61:             responses[f"set password {password}\r".encode()] = (
62:                 b"Please enter current administrator password: "
63:             )
64:         else:
65:             responses[b"unset password\r"] = ADMIN_PROMPT
66: 
67:         connection = SerialConnection(responses)
68:         terminal = Terminal(connection, logger)
69:         commander = FOSCommander(terminal, logger)
70:         credentials = Credentials("admin", "oldpass")
71:         driver = FOSCliDriver(
72:             terminal, commander, credentials, logger, "bootstrap",
73:             MagicMock(), MagicMock(), allow_credential_recovery=True,
74:         )
75: 
76:         def activate_desired():
77:             driver.remember_current_credentials()
78:             credentials.username = username
79:             credentials.password = password
80: 
81:         vm = SimpleNamespace(
82:             desired_credentials=Credentials(username, password),
83:             activate_desired_credentials=activate_desired,
84:         )
85:         admin = CredentialsFeature(vm, commander)
86:         following = RecordingFeature(commander, "following", ["probe"])
87:         commander.start([admin, following])
88:         self.addCleanup(lambda: terminal.close() if not connection.closed else None)
89:         return connection, commander, driver, admin, following
90: 
91:     def run_driver(self, driver):
92:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
93:                 patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.15):
94:             driver.process_state()
95: 
96:     def test_logout_and_relogin_after_committing_credentials(self):
97:         for username, password in (("admin", "newpass"), ("admin", ""),
98:                                    ("operator", "newpass")):
99:             with self.subTest(username=username, password_set=bool(password)):
100:                 conn, cmd, driver, admin, following = self.make_stack(
101:                     username=username, password=password,
102:                 )
103:                 self.run_driver(driver)
104:                 self.assertTrue(cmd.ready)
105:                 self.assertTrue(admin.completed)
106:                 self.assertTrue(following.completed)
107:                 logout = conn.writes.index(b"exit\r")
108:                 self.assertEqual(conn.writes[logout - 1], b"end\r")
109:                 self.assertEqual(conn.writes[logout + 1:], [
110:                     (username + "\r").encode(),
111:                     (password + "\r").encode(),
112:                     b"probe\r",
113:                 ])
114:                 self.assertEqual(conn.writes.count(b"exit\r"), 1)
115: 
116:     def test_later_features_wait_for_authentication(self):
117:         conn, cmd, driver, admin, following = self.make_stack(authenticate=False)
118:         self.run_driver(driver)
119:         self.assertIn(b"exit\r", conn.writes)
120:         self.assertIn(b"newpass\r", conn.writes)
121:         self.assertNotIn(b"probe\r", conn.writes)
122:         self.assertFalse(admin.completed)
123:         self.assertFalse(following.completed)
124:         self.assertFalse(cmd.ready)
125: 
126:     def test_fortios_logout_at_commit_does_not_replay_password_change(self):
127:         for commit_command in ("next", "end"):
128:             with self.subTest(commit_command=commit_command):
129:                 conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)
130:                 self.run_driver(driver)
131:                 self.assertTrue(cmd.ready)
132:                 self.assertTrue(admin.completed)
133:                 self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
134:                 self.assertEqual(conn.writes.count(b"exit\r"), 1)
135:                 self.assertEqual(conn.writes.count(b"newpass\r"), 2)
136: 
137:     def test_logout_must_return_to_login(self):
138:         conn, _, driver, admin, _ = self.make_stack(exit_works=False)
139:         with self.assertRaisesRegex(RuntimeError, "expected PROVIDE_USERNAME"):
140:             self.run_driver(driver)
141:         self.assertFalse(admin.completed)
142:         self.assertNotIn(b"probe\r", conn.writes)
143: 
144:     def test_rejected_credentials_do_not_start_later_features(self):
145:         conn, _, driver, admin, _ = self.make_stack(reject=True)
146:         with self.assertRaisesRegex(RuntimeError, "Credential rejected"):
147:             self.run_driver(driver)
148:         self.assertFalse(admin.completed)
149:         self.assertNotIn(b"probe\r", conn.writes)
150:         self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
151: 
152: 
153: if __name__ == "__main__":
154:     unittest.main()

(End of file - total 154 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d6a66e001rZ3p1npu0C6vmx",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d68fc6001YUuZT3OH6uecsd",
  "callID": "call_2e382d8b546d493682237f77",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_admin_credentials.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_admin_credentials.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from types import SimpleNamespace\n7: from unittest.mock import MagicMock, patch\n8: \n9: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n10: \n11: from fortinet.common.common import Credentials\n12: from fortinet.common.features.credentials import CredentialsFeature\n13: from fortinet.common.fos_cli_driver import FOSCliDriver\n14: from fortinet.common.fos_commander import FOSCommander\n15: from fortinet.common.terminal import Terminal\n16: from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n17: \n18: \n19: LOGIN = b\"fw login:\\r\\n\"\n20: READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n21: ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n22: \n23: \n24: class AdminCredentialsTests(unittest.TestCase):\n25:     def make_stack(self, *, password=\"newpass\", username=\"admin\",\n26:                    auto_logout=None, authenticate=True, reject=False,\n27:                    exit_works=True):\n28:         logger = MagicMock()\n29:         policy_prompt = b\"fw (password-policy) #\\r\\n\"\n30:         old_password_responses = [READY]\n31:         if password:\n32:             old_password_responses.append(ADMIN_PROMPT)\n33:         old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n34:         end_count = 0\n35: \n36:         def end_response():\n37:             nonlocal end_count\n38:             end_count += 1\n39:             return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n40: \n41:         login_reply = None if not authenticate else (\n42:             b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n43:         )\n44:         responses = {\n45:             b\"admin\\r\": b\"Password:\",\n46:             b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n47:             b\"config system password-policy\\r\": policy_prompt,\n48:             b\"set status disable\\r\": policy_prompt,\n49:             b\"config system admin\\r\": ADMIN_PROMPT,\n50:             f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n51:             b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n52:             b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n53:             b\"end\\r\": end_response,\n54:             b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n55:             b\"probe\\r\": b\"fw #\\r\\n\",\n56:             (password + \"\\r\").encode(): login_reply,\n57:         }\n58:         if username != \"admin\":\n59:             responses[(username + \"\\r\").encode()] = b\"Password:\"\n60:         if password:\n61:             responses[f\"set password {password}\\r\".encode()] = (\n62:                 b\"Please enter current administrator password: \"\n63:             )\n64:         else:\n65:             responses[b\"unset password\\r\"] = ADMIN_PROMPT\n66: \n67:         connection = SerialConnection(responses)\n68:         terminal = Terminal(connection, logger)\n69:         commander = FOSCommander(terminal, logger)\n70:         credentials = Credentials(\"admin\", \"oldpass\")\n71:         driver = FOSCliDriver(\n72:             terminal, commander, credentials, logger, \"bootstrap\",\n73:             MagicMock(), MagicMock(), allow_credential_recovery=True,\n74:         )\n75: \n76:         def activate_desired():\n77:             driver.remember_current_credentials()\n78:             credentials.username = username\n79:             credentials.password = password\n80: \n81:         vm = SimpleNamespace(\n82:             desired_credentials=Credentials(username, password),\n83:             activate_desired_credentials=activate_desired,\n84:         )\n85:         admin = CredentialsFeature(vm, commander)\n86:         following = RecordingFeature(commander, \"following\", [\"probe\"])\n87:         commander.start([admin, following])\n88:         self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n89:         return connection, commander, driver, admin, following\n90: \n91:     def run_driver(self, driver):\n92:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n93:                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n94:             driver.process_state()\n95: \n96:     def test_logout_and_relogin_after_committing_credentials(self):\n97:         for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n98:                                    (\"operator\", \"newpass\")):\n99:             with self.subTest(username=username, password_set=bool(password)):\n100:                 conn, cmd, driver, admin, following = self.make_stack(\n101:                     username=username, password=password,\n102:                 )\n103:                 self.run_driver(driver)\n104:                 self.assertTrue(cmd.ready)\n105:                 self.assertTrue(admin.completed)\n106:                 self.assertTrue(following.completed)\n107:                 logout = conn.writes.index(b\"exit\\r\")\n108:                 self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n109:                 self.assertEqual(conn.writes[logout + 1:], [\n110:                     (username + \"\\r\").encode(),\n111:                     (password + \"\\r\").encode(),\n112:                     b\"probe\\r\",\n113:                 ])\n114:                 self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n115: \n116:     def test_later_features_wait_for_authentication(self):\n117:         conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n118:         self.run_driver(driver)\n119:         self.assertIn(b\"exit\\r\", conn.writes)\n120:         self.assertIn(b\"newpass\\r\", conn.writes)\n121:         self.assertNotIn(b\"probe\\r\", conn.writes)\n122:         self.assertFalse(admin.completed)\n123:         self.assertFalse(following.completed)\n124:         self.assertFalse(cmd.ready)\n125: \n126:     def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n127:         for commit_command in (\"next\", \"end\"):\n128:             with self.subTest(commit_command=commit_command):\n129:                 conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n130:                 self.run_driver(driver)\n131:                 self.assertTrue(cmd.ready)\n132:                 self.assertTrue(admin.completed)\n133:                 self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n134:                 self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n135:                 self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n136: \n137:     def test_logout_must_return_to_login(self):\n138:         conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n139:         with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n140:             self.run_driver(driver)\n141:         self.assertFalse(admin.completed)\n142:         self.assertNotIn(b\"probe\\r\", conn.writes)\n143: \n144:     def test_rejected_credentials_do_not_start_later_features(self):\n145:         conn, _, driver, admin, _ = self.make_stack(reject=True)\n146:         with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n147:             self.run_driver(driver)\n148:         self.assertFalse(admin.completed)\n149:         self.assertNotIn(b\"probe\\r\", conn.writes)\n150:         self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n151: \n152: \n153: if __name__ == \"__main__\":\n154:     unittest.main()\n\n(End of file - total 154 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_admin_credentials.py",
    "metadata": {
      "preview": "\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom unittest.mock import MagicMock, patch\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.common import Credentials\nfrom fortinet.common.features.credentials import CredentialsFeature\nfrom fortinet.common.fos_cli_driver import FOSCliDriver\nfrom fortinet.common.fos_commander import FOSCommander\nfrom fortinet.common.terminal import Terminal\nfrom fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n\n\nLOGIN = b\"fw login:\\r\\n\"\nREADY = b\"Welcome!\\r\\nfw #\\r\\n\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_admin_credentials.py",
        "text": "\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom unittest.mock import MagicMock, patch\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.common import Credentials\nfrom fortinet.common.features.credentials import CredentialsFeature\nfrom fortinet.common.fos_cli_driver import FOSCliDriver\nfrom fortinet.common.fos_commander import FOSCommander\nfrom fortinet.common.terminal import Terminal\nfrom fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n\n\nLOGIN = b\"fw login:\\r\\n\"\nREADY = b\"Welcome!\\r\\nfw #\\r\\n\"\nADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n\n\nclass AdminCredentialsTests(unittest.TestCase):\n    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n                   auto_logout=None, authenticate=True, reject=False,\n                   exit_works=True):\n        logger = MagicMock()\n        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n        old_password_responses = [READY]\n        if password:\n            old_password_responses.append(ADMIN_PROMPT)\n        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n        end_count = 0\n\n        def end_response():\n            nonlocal end_count\n            end_count += 1\n            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n\n        login_reply = None if not authenticate else (\n            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n        )\n        responses = {\n            b\"admin\\r\": b\"Password:\",\n            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n            b\"config system password-policy\\r\": policy_prompt,\n            b\"set status disable\\r\": policy_prompt,\n            b\"config system admin\\r\": ADMIN_PROMPT,\n            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n            b\"end\\r\": end_response,\n            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n            b\"probe\\r\": b\"fw #\\r\\n\",\n            (password + \"\\r\").encode(): login_reply,\n        }\n        if username != \"admin\":\n            responses[(username + \"\\r\").encode()] = b\"Password:\"\n        if password:\n            responses[f\"set password {password}\\r\".encode()] = (\n                b\"Please enter current administrator password: \"\n            )\n        else:\n            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n\n        connection = SerialConnection(responses)\n        terminal = Terminal(connection, logger)\n        commander = FOSCommander(terminal, logger)\n        credentials = Credentials(\"admin\", \"oldpass\")\n        driver = FOSCliDriver(\n            terminal, commander, credentials, logger, \"bootstrap\",\n            MagicMock(), MagicMock(), allow_credential_recovery=True,\n        )\n\n        def activate_desired():\n            driver.remember_current_credentials()\n            credentials.username = username\n            credentials.password = password\n\n        vm = SimpleNamespace(\n            desired_credentials=Credentials(username, password),\n            activate_desired_credentials=activate_desired,\n        )\n        admin = CredentialsFeature(vm, commander)\n        following = RecordingFeature(commander, \"following\", [\"probe\"])\n        commander.start([admin, following])\n        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n        return connection, commander, driver, admin, following\n\n    def run_driver(self, driver):\n        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n            driver.process_state()\n\n    def test_logout_and_relogin_after_committing_credentials(self):\n        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n                                   (\"operator\", \"newpass\")):\n            with self.subTest(username=username, password_set=bool(password)):\n                conn, cmd, driver, admin, following = self.make_stack(\n                    username=username, password=password,\n                )\n                self.run_driver(driver)\n                self.assertTrue(cmd.ready)\n                self.assertTrue(admin.completed)\n                self.assertTrue(following.completed)\n                logout = conn.writes.index(b\"exit\\r\")\n                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n                self.assertEqual(conn.writes[logout + 1:], [\n                    (username + \"\\r\").encode(),\n                    (password + \"\\r\").encode(),\n                    b\"probe\\r\",\n                ])\n                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n\n    def test_later_features_wait_for_authentication(self):\n        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n        self.run_driver(driver)\n        self.assertIn(b\"exit\\r\", conn.writes)\n        self.assertIn(b\"newpass\\r\", conn.writes)\n        self.assertNotIn(b\"probe\\r\", conn.writes)\n        self.assertFalse(admin.completed)\n        self.assertFalse(following.completed)\n        self.assertFalse(cmd.ready)\n\n    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n        for commit_command in (\"next\", \"end\"):\n            with self.subTest(commit_command=commit_command):\n                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n                self.run_driver(driver)\n                self.assertTrue(cmd.ready)\n                self.assertTrue(admin.completed)\n                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n\n    def test_logout_must_return_to_login(self):\n        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n            self.run_driver(driver)\n        self.assertFalse(admin.completed)\n        self.assertNotIn(b\"probe\\r\", conn.writes)\n\n    def test_rejected_credentials_do_not_start_later_features(self):\n        conn, _, driver, admin, _ = self.make_stack(reject=True)\n        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n            self.run_driver(driver)\n        self.assertFalse(admin.completed)\n        self.assertNotIn(b\"probe\\r\", conn.writes)\n        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 154,
        "totalLines": 154,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716561522,
      "end": 1793716561526
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_recovery.py"
}

Output

<path>/source/head/fortinet/tests/test_common_recovery.py</path>
<type>file</type>
<content>
1: """Bounded recovery after a scope exit or an interrupted CLI session."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from unittest.mock import MagicMock
7: 
8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
9: 
10: from fortinet.common.cli_commands import (  # noqa: E402
11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,
12:     EditBlock, SessionLossAction,
13: )
14: from fortinet.common.common import FOSCliState  # noqa: E402
15: from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402
16: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
17: from fortinet.common.terminal import Data  # noqa: E402
18: 
19: 
20: IP_COMMAND = "set ip 10.0.52.4/24"
21: ACCESS_COMMAND = "set allowaccess ping https ssh http"
22: 
23: 
24: class RecordingFeature(Feature):
25:     def __init__(self, commander, block, context_action=None):
26:         super().__init__(None, commander, "management")
27:         self.block = block
28:         self.context_action = context_action
29:         self.losses = []
30:         self.attempts = []
31:         self.executed = []
32: 
33:     def activate(self):
34:         self.commander.submit_block(self, self.block)
35: 
36:     def on_command_dispatched(self, attempt):
37:         super().on_command_dispatched(attempt)
38:         self.attempts.append(attempt)
39: 
40:     def on_command_executed(self, attempt, state):
41:         self.executed.append(attempt.spec.line)
42: 
43:     def on_context_loss(self, attempt):
44:         self.losses.append(attempt)
45:         if self.context_action is not None:
46:             return self.context_action
47:         return super().on_context_loss(attempt)
48: 
49: 
50: class RecoveryTests(unittest.TestCase):
51:     def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,
52:                        context_action=None, following=False):
53:         terminal = MagicMock()
54:         commander = FOSCommander(terminal, MagicMock(), continue_on_error)
55:         block = ConfigBlock("system interface", [EditBlock("port1", [
56:             ip_command, ACCESS_COMMAND,
57:         ])])
58:         feature = RecordingFeature(commander, block, context_action)
59:         features = [feature]
60:         if following:
61:             features.append(RecordingFeature(
62:                 commander, CommandSequence("following", ["get system status"])
63:             ))
64:         commander.start(features)
65:         return commander, terminal, feature
66: 
67:     def prompt(self, commander, context=None):
68:         scope = f" ({context})" if context else ""
69:         commander.on_state(FOSCliState.CMD_PROMPT, Data(
70:             f"FGT-VM64-KVM-NSVHDM{scope} (Interim)#".encode()
71:         ))
72: 
73:     def enter_interface(self, commander):
74:         self.prompt(commander, "interface")
75:         self.prompt(commander, "port1")
76: 
77:     def finish_interface(self, commander):
78:         self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
79:         self.prompt(commander, "port1")  # allowaccess succeeds; dispatch next.
80:         self.prompt(commander, "interface")  # next succeeds; dispatch end.
81:         self.prompt(commander)  # end succeeds.
82: 
83:     @staticmethod
84:     def writes(terminal):
85:         return [call.args[0] for call in terminal.write.call_args_list]
86: 
87:     def reconnect(self, commander):
88:         commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b"Welcome!"))
89:         self.prompt(commander)
90: 
91:     def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):
92:         commander, terminal, feature = self.make_commander()
93:         self.prompt(commander)
94:         self.enter_interface(commander)
95:         self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.
96:         self.assertEqual(self.writes(terminal), [
97:             "config system interface\r", "edit port1\r", IP_COMMAND + "\r",
98:             "config system interface\r",
99:         ])
100:         self.assertNotIn(IP_COMMAND, feature.executed)
101:         self.assertEqual(feature.losses[0].prompt_context_before, ("port1", "Interim"))
102:         self.assertEqual(feature.losses[0].prompt_context_after, ("Interim",))
103:         self.enter_interface(commander)
104:         self.finish_interface(commander)
105:         ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]
106:         self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])
107:         self.assertTrue(feature.completed)
108:         self.assertTrue(commander.ready)
109: 
110:     def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):
111:         for best_effort in (False, True):
112:             with self.subTest(best_effort=best_effort):
113:                 commander, terminal, feature = self.make_commander(
114:                     continue_on_error=best_effort, following=True,
115:                 )
116:                 self.prompt(commander)
117:                 self.enter_interface(commander)
118:                 self.prompt(commander)
119:                 self.enter_interface(commander)
120:                 if best_effort:
121:                     self.prompt(commander)
122:                     self.assertIn("retry limit", commander.feature_errors[0][1])
123:                     self.assertEqual(self.writes(terminal)[-1], "get system status\r")
124:                 else:
125:                     with self.assertRaisesRegex(RuntimeError, "retry limit"):
126:                         self.prompt(commander)
127:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
128:                 self.assertNotIn(ACCESS_COMMAND + "\r", self.writes(terminal))
129:                 self.assertFalse(feature.completed)
130: 
131:     def test_session_and_context_loss_share_the_same_command_retry_allowance(self):
132:         commander, terminal, feature = self.make_commander()
133:         self.prompt(commander)
134:         self.enter_interface(commander)
135:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
136:         self.reconnect(commander)
137:         self.enter_interface(commander)
138:         with self.assertRaisesRegex(RuntimeError, "retry limit"):
139:             self.prompt(commander)
140:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
141:         self.assertEqual(feature.losses[0].retry_count, 1)
142: 
143:     def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):
144:         commander, terminal, _feature = self.make_commander(
145:             continue_on_error=True, following=True,
146:         )
147:         self.prompt(commander)
148:         self.enter_interface(commander)
149:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
150:         self.reconnect(commander)
151:         self.enter_interface(commander)
152:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
153:         self.assertNotIn("get system status\r", self.writes(terminal))
154:         self.reconnect(commander)
155:         self.assertEqual(self.writes(terminal)[-1], "get system status\r")
156:         self.assertIn("retry limit", commander.feature_errors[0][1])
157: 
158:     def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):
159:         commander, terminal, _feature = self.make_commander(
160:             continue_on_error=True, following=True,
161:         )
162:         self.prompt(commander)
163:         self.enter_interface(commander)
164:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
165:         self.prompt(commander)  # Successful login returns a prompt, no Welcome.
166:         self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
167:         self.enter_interface(commander)
168:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
169:         self.assertNotIn("get system status\r", self.writes(terminal))
170:         self.prompt(commander)  # Exhaustion is handled at this usable prompt.
171:         self.assertEqual(self.writes(terminal)[-1], "get system status\r")
172:         self.assertIn("retry limit", commander.feature_errors[0][1])
173: 
174:     def test_each_command_position_gets_one_recovery(self):
175:         commander, terminal, feature = self.make_commander()
176:         self.prompt(commander)
177:         self.enter_interface(commander)
178:         self.prompt(commander)  # First loss: IP command.
179:         self.enter_interface(commander)
180:         self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
181:         self.prompt(commander)  # Second loss: allowaccess command.
182:         self.enter_interface(commander)
183:         self.finish_interface(commander)
184:         self.assertTrue(feature.completed)
185:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 3)
186:         self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + "\r"), 2)
187: 
188:     def test_feature_can_decline_replay_without_running_session_loss_callback(self):
189:         for explicit_policy in (False, True):
190:             with self.subTest(explicit_policy=explicit_policy):
191:                 spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)
192:                 commander, terminal, feature = self.make_commander(
193:                     ip_command=IP_COMMAND if explicit_policy else spec,
194:                     context_action=ContextLossAction.FAIL if explicit_policy else None,
195:                 )
196:                 feature.on_session_loss = MagicMock()
197:                 self.prompt(commander)
198:                 self.enter_interface(commander)
199:                 with self.assertRaisesRegex(RuntimeError, "feature declined replay"):
200:                     self.prompt(commander)
201:                 feature.on_session_loss.assert_not_called()
202:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
203: 
204:     def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):
205:         spec = CommandSpec(
206:             IP_COMMAND, session_loss=SessionLossAction.CONTINUE,
207:             context_loss=ContextLossAction.RESTART_BLOCK,
208:         )
209:         commander, _terminal, feature = self.make_commander(ip_command=spec)
210:         feature.on_session_loss = MagicMock()
211:         self.prompt(commander)
212:         self.enter_interface(commander)
213:         self.prompt(commander)
214:         self.enter_interface(commander)
215:         self.finish_interface(commander)
216:         self.assertTrue(feature.completed)
217:         feature.on_session_loss.assert_not_called()
218: 
219:     def test_partial_scope_is_aborted_once_before_replay(self):
220:         commander, terminal, feature = self.make_commander()
221:         self.prompt(commander)
222:         self.enter_interface(commander)
223:         self.prompt(commander, "interface")  # Only the edit context disappeared.
224:         self.assertEqual(self.writes(terminal)[-1], "abort\r")
225:         self.prompt(commander)
226:         self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
227:         self.enter_interface(commander)
228:         self.finish_interface(commander)
229:         self.assertTrue(feature.completed)
230:         self.assertNotIn("abort", feature.executed)
231:         self.assertNotIn("abort", [item.spec.line for item in feature.attempts])
232: 
233:     def test_failed_context_reset_does_not_loop(self):
234:         commander, terminal, _feature = self.make_commander()
235:         self.prompt(commander)
236:         self.enter_interface(commander)
237:         self.prompt(commander, "interface")
238:         with self.assertRaisesRegex(RuntimeError, "Unable to restore CLI context"):
239:             self.prompt(commander, "interface")
240:         self.assertEqual(self.writes(terminal).count("abort\r"), 1)
241:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
242: 
243:     def test_session_loss_during_context_reset_resumes_after_login(self):
244:         commander, terminal, feature = self.make_commander()
245:         self.prompt(commander)
246:         self.enter_interface(commander)
247:         self.prompt(commander, "interface")
248:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
249:         self.reconnect(commander)
250:         self.enter_interface(commander)
251:         self.finish_interface(commander)
252:         self.assertTrue(feature.completed)
253:         self.assertEqual(self.writes(terminal).count("abort\r"), 1)
254: 
255:     def test_cleanup_session_loss_is_bounded(self):
256:         terminal = MagicMock()
257:         commander = FOSCommander(terminal, MagicMock())
258:         feature = RecordingFeature(commander, CommandSequence("work", ["get status"]))
259:         commander.register_cleanup(feature, CleanupAction(
260:             "cleanup", CommandSequence("cleanup", ["get cleanup"]),
261:         ))
262:         commander.start([feature])
263:         self.prompt(commander)
264:         self.prompt(commander)  # Begin cleanup after the feature completes.
265:         commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
266:         self.reconnect(commander)
267:         with self.assertRaisesRegex(RuntimeError, "retry limit"):
268:             commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
269:         self.assertEqual(self.writes(terminal).count("get cleanup\r"), 2)
270: 
271:     def test_newly_submitted_block_resets_retry_allowance(self):
272:         terminal = MagicMock()
273:         commander = FOSCommander(terminal, MagicMock())
274:         feature = StaticFeature(None, commander, "two-blocks", [
275:             ConfigBlock("system global", ["set alias first"]),
276:             ConfigBlock("system global", ["set alias second"]),
277:         ])
278:         commander.start([feature])
279:         self.prompt(commander)
280:         for _index in range(2):
281:             self.prompt(commander, "global")
282:             self.prompt(commander)  # Lost context: retry this block.
283:             self.prompt(commander, "global")
284:             self.prompt(commander, "global")
285:             self.prompt(commander)  # End this block and start the next one.
286:         self.assertTrue(feature.completed)
287:         self.assertEqual(self.writes(terminal).count("set alias first\r"), 2)
288:         self.assertEqual(self.writes(terminal).count("set alias second\r"), 2)
289: 
290: 
291: if __name__ == "__main__":
292:     unittest.main()

(End of file - total 292 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d6a69b001vdy0Ut1IwR63t2",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d68fc6001YUuZT3OH6uecsd",
  "callID": "call_0d3ac79d1b3f49e49000c64e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_recovery.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_recovery.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from unittest.mock import MagicMock\n7: \n8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n9: \n10: from fortinet.common.cli_commands import (  # noqa: E402\n11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n12:     EditBlock, SessionLossAction,\n13: )\n14: from fortinet.common.common import FOSCliState  # noqa: E402\n15: from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n16: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n17: from fortinet.common.terminal import Data  # noqa: E402\n18: \n19: \n20: IP_COMMAND = \"set ip 10.0.52.4/24\"\n21: ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n22: \n23: \n24: class RecordingFeature(Feature):\n25:     def __init__(self, commander, block, context_action=None):\n26:         super().__init__(None, commander, \"management\")\n27:         self.block = block\n28:         self.context_action = context_action\n29:         self.losses = []\n30:         self.attempts = []\n31:         self.executed = []\n32: \n33:     def activate(self):\n34:         self.commander.submit_block(self, self.block)\n35: \n36:     def on_command_dispatched(self, attempt):\n37:         super().on_command_dispatched(attempt)\n38:         self.attempts.append(attempt)\n39: \n40:     def on_command_executed(self, attempt, state):\n41:         self.executed.append(attempt.spec.line)\n42: \n43:     def on_context_loss(self, attempt):\n44:         self.losses.append(attempt)\n45:         if self.context_action is not None:\n46:             return self.context_action\n47:         return super().on_context_loss(attempt)\n48: \n49: \n50: class RecoveryTests(unittest.TestCase):\n51:     def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n52:                        context_action=None, following=False):\n53:         terminal = MagicMock()\n54:         commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n55:         block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n56:             ip_command, ACCESS_COMMAND,\n57:         ])])\n58:         feature = RecordingFeature(commander, block, context_action)\n59:         features = [feature]\n60:         if following:\n61:             features.append(RecordingFeature(\n62:                 commander, CommandSequence(\"following\", [\"get system status\"])\n63:             ))\n64:         commander.start(features)\n65:         return commander, terminal, feature\n66: \n67:     def prompt(self, commander, context=None):\n68:         scope = f\" ({context})\" if context else \"\"\n69:         commander.on_state(FOSCliState.CMD_PROMPT, Data(\n70:             f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n71:         ))\n72: \n73:     def enter_interface(self, commander):\n74:         self.prompt(commander, \"interface\")\n75:         self.prompt(commander, \"port1\")\n76: \n77:     def finish_interface(self, commander):\n78:         self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n79:         self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n80:         self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n81:         self.prompt(commander)  # end succeeds.\n82: \n83:     @staticmethod\n84:     def writes(terminal):\n85:         return [call.args[0] for call in terminal.write.call_args_list]\n86: \n87:     def reconnect(self, commander):\n88:         commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n89:         self.prompt(commander)\n90: \n91:     def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n92:         commander, terminal, feature = self.make_commander()\n93:         self.prompt(commander)\n94:         self.enter_interface(commander)\n95:         self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n96:         self.assertEqual(self.writes(terminal), [\n97:             \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n98:             \"config system interface\\r\",\n99:         ])\n100:         self.assertNotIn(IP_COMMAND, feature.executed)\n101:         self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n102:         self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n103:         self.enter_interface(commander)\n104:         self.finish_interface(commander)\n105:         ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n106:         self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n107:         self.assertTrue(feature.completed)\n108:         self.assertTrue(commander.ready)\n109: \n110:     def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n111:         for best_effort in (False, True):\n112:             with self.subTest(best_effort=best_effort):\n113:                 commander, terminal, feature = self.make_commander(\n114:                     continue_on_error=best_effort, following=True,\n115:                 )\n116:                 self.prompt(commander)\n117:                 self.enter_interface(commander)\n118:                 self.prompt(commander)\n119:                 self.enter_interface(commander)\n120:                 if best_effort:\n121:                     self.prompt(commander)\n122:                     self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n123:                     self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n124:                 else:\n125:                     with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n126:                         self.prompt(commander)\n127:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n128:                 self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n129:                 self.assertFalse(feature.completed)\n130: \n131:     def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n132:         commander, terminal, feature = self.make_commander()\n133:         self.prompt(commander)\n134:         self.enter_interface(commander)\n135:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n136:         self.reconnect(commander)\n137:         self.enter_interface(commander)\n138:         with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n139:             self.prompt(commander)\n140:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n141:         self.assertEqual(feature.losses[0].retry_count, 1)\n142: \n143:     def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n144:         commander, terminal, _feature = self.make_commander(\n145:             continue_on_error=True, following=True,\n146:         )\n147:         self.prompt(commander)\n148:         self.enter_interface(commander)\n149:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n150:         self.reconnect(commander)\n151:         self.enter_interface(commander)\n152:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n153:         self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n154:         self.reconnect(commander)\n155:         self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n156:         self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n157: \n158:     def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n159:         commander, terminal, _feature = self.make_commander(\n160:             continue_on_error=True, following=True,\n161:         )\n162:         self.prompt(commander)\n163:         self.enter_interface(commander)\n164:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n165:         self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n166:         self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n167:         self.enter_interface(commander)\n168:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n169:         self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n170:         self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n171:         self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n172:         self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n173: \n174:     def test_each_command_position_gets_one_recovery(self):\n175:         commander, terminal, feature = self.make_commander()\n176:         self.prompt(commander)\n177:         self.enter_interface(commander)\n178:         self.prompt(commander)  # First loss: IP command.\n179:         self.enter_interface(commander)\n180:         self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n181:         self.prompt(commander)  # Second loss: allowaccess command.\n182:         self.enter_interface(commander)\n183:         self.finish_interface(commander)\n184:         self.assertTrue(feature.completed)\n185:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n186:         self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n187: \n188:     def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n189:         for explicit_policy in (False, True):\n190:             with self.subTest(explicit_policy=explicit_policy):\n191:                 spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n192:                 commander, terminal, feature = self.make_commander(\n193:                     ip_command=IP_COMMAND if explicit_policy else spec,\n194:                     context_action=ContextLossAction.FAIL if explicit_policy else None,\n195:                 )\n196:                 feature.on_session_loss = MagicMock()\n197:                 self.prompt(commander)\n198:                 self.enter_interface(commander)\n199:                 with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n200:                     self.prompt(commander)\n201:                 feature.on_session_loss.assert_not_called()\n202:                 self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n203: \n204:     def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n205:         spec = CommandSpec(\n206:             IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n207:             context_loss=ContextLossAction.RESTART_BLOCK,\n208:         )\n209:         commander, _terminal, feature = self.make_commander(ip_command=spec)\n210:         feature.on_session_loss = MagicMock()\n211:         self.prompt(commander)\n212:         self.enter_interface(commander)\n213:         self.prompt(commander)\n214:         self.enter_interface(commander)\n215:         self.finish_interface(commander)\n216:         self.assertTrue(feature.completed)\n217:         feature.on_session_loss.assert_not_called()\n218: \n219:     def test_partial_scope_is_aborted_once_before_replay(self):\n220:         commander, terminal, feature = self.make_commander()\n221:         self.prompt(commander)\n222:         self.enter_interface(commander)\n223:         self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n224:         self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n225:         self.prompt(commander)\n226:         self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n227:         self.enter_interface(commander)\n228:         self.finish_interface(commander)\n229:         self.assertTrue(feature.completed)\n230:         self.assertNotIn(\"abort\", feature.executed)\n231:         self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n232: \n233:     def test_failed_context_reset_does_not_loop(self):\n234:         commander, terminal, _feature = self.make_commander()\n235:         self.prompt(commander)\n236:         self.enter_interface(commander)\n237:         self.prompt(commander, \"interface\")\n238:         with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n239:             self.prompt(commander, \"interface\")\n240:         self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n241:         self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n242: \n243:     def test_session_loss_during_context_reset_resumes_after_login(self):\n244:         commander, terminal, feature = self.make_commander()\n245:         self.prompt(commander)\n246:         self.enter_interface(commander)\n247:         self.prompt(commander, \"interface\")\n248:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n249:         self.reconnect(commander)\n250:         self.enter_interface(commander)\n251:         self.finish_interface(commander)\n252:         self.assertTrue(feature.completed)\n253:         self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n254: \n255:     def test_cleanup_session_loss_is_bounded(self):\n256:         terminal = MagicMock()\n257:         commander = FOSCommander(terminal, MagicMock())\n258:         feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n259:         commander.register_cleanup(feature, CleanupAction(\n260:             \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n261:         ))\n262:         commander.start([feature])\n263:         self.prompt(commander)\n264:         self.prompt(commander)  # Begin cleanup after the feature completes.\n265:         commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n266:         self.reconnect(commander)\n267:         with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n268:             commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n269:         self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n270: \n271:     def test_newly_submitted_block_resets_retry_allowance(self):\n272:         terminal = MagicMock()\n273:         commander = FOSCommander(terminal, MagicMock())\n274:         feature = StaticFeature(None, commander, \"two-blocks\", [\n275:             ConfigBlock(\"system global\", [\"set alias first\"]),\n276:             ConfigBlock(\"system global\", [\"set alias second\"]),\n277:         ])\n278:         commander.start([feature])\n279:         self.prompt(commander)\n280:         for _index in range(2):\n281:             self.prompt(commander, \"global\")\n282:             self.prompt(commander)  # Lost context: retry this block.\n283:             self.prompt(commander, \"global\")\n284:             self.prompt(commander, \"global\")\n285:             self.prompt(commander)  # End this block and start the next one.\n286:         self.assertTrue(feature.completed)\n287:         self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n288:         self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n289: \n290: \n291: if __name__ == \"__main__\":\n292:     unittest.main()\n\n(End of file - total 292 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_recovery.py",
    "metadata": {
      "preview": "\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n    EditBlock, SessionLossAction,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nIP_COMMAND = \"set ip 10.0.52.4/24\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_recovery.py",
        "text": "\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n    EditBlock, SessionLossAction,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nIP_COMMAND = \"set ip 10.0.52.4/24\"\nACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, block, context_action=None):\n        super().__init__(None, commander, \"management\")\n        self.block = block\n        self.context_action = context_action\n        self.losses = []\n        self.attempts = []\n        self.executed = []\n\n    def activate(self):\n        self.commander.submit_block(self, self.block)\n\n    def on_command_dispatched(self, attempt):\n        super().on_command_dispatched(attempt)\n        self.attempts.append(attempt)\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append(attempt.spec.line)\n\n    def on_context_loss(self, attempt):\n        self.losses.append(attempt)\n        if self.context_action is not None:\n            return self.context_action\n        return super().on_context_loss(attempt)\n\n\nclass RecoveryTests(unittest.TestCase):\n    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n                       context_action=None, following=False):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n            ip_command, ACCESS_COMMAND,\n        ])])\n        feature = RecordingFeature(commander, block, context_action)\n        features = [feature]\n        if following:\n            features.append(RecordingFeature(\n                commander, CommandSequence(\"following\", [\"get system status\"])\n            ))\n        commander.start(features)\n        return commander, terminal, feature\n\n    def prompt(self, commander, context=None):\n        scope = f\" ({context})\" if context else \"\"\n        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n        ))\n\n    def enter_interface(self, commander):\n        self.prompt(commander, \"interface\")\n        self.prompt(commander, \"port1\")\n\n    def finish_interface(self, commander):\n        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n        self.prompt(commander)  # end succeeds.\n\n    @staticmethod\n    def writes(terminal):\n        return [call.args[0] for call in terminal.write.call_args_list]\n\n    def reconnect(self, commander):\n        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n        self.prompt(commander)\n\n    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n        self.assertEqual(self.writes(terminal), [\n            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n            \"config system interface\\r\",\n        ])\n        self.assertNotIn(IP_COMMAND, feature.executed)\n        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n        self.assertTrue(feature.completed)\n        self.assertTrue(commander.ready)\n\n    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n        for best_effort in (False, True):\n            with self.subTest(best_effort=best_effort):\n                commander, terminal, feature = self.make_commander(\n                    continue_on_error=best_effort, following=True,\n                )\n                self.prompt(commander)\n                self.enter_interface(commander)\n                self.prompt(commander)\n                self.enter_interface(commander)\n                if best_effort:\n                    self.prompt(commander)\n                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n                else:\n                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n                        self.prompt(commander)\n                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n                self.assertFalse(feature.completed)\n\n    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        self.enter_interface(commander)\n        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n            self.prompt(commander)\n        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n        self.assertEqual(feature.losses[0].retry_count, 1)\n\n    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n        commander, terminal, _feature = self.make_commander(\n            continue_on_error=True, following=True,\n        )\n        self.prompt(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n        self.reconnect(commander)\n        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n\n    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n        commander, terminal, _feature = self.make_commander(\n            continue_on_error=True, following=True,\n        )\n        self.prompt(commander)\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n        self.enter_interface(commander)\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n\n    def test_each_command_position_gets_one_recovery(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander)  # First loss: IP command.\n        self.enter_interface(commander)\n        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n        self.prompt(commander)  # Second loss: allowaccess command.\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n\n    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n        for explicit_policy in (False, True):\n            with self.subTest(explicit_policy=explicit_policy):\n                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n                commander, terminal, feature = self.make_commander(\n                    ip_command=IP_COMMAND if explicit_policy else spec,\n                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n                )\n                feature.on_session_loss = MagicMock()\n                self.prompt(commander)\n                self.enter_interface(commander)\n                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n                    self.prompt(commander)\n                feature.on_session_loss.assert_not_called()\n                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n\n    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n        spec = CommandSpec(\n            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n            context_loss=ContextLossAction.RESTART_BLOCK,\n        )\n        commander, _terminal, feature = self.make_commander(ip_command=spec)\n        feature.on_session_loss = MagicMock()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        feature.on_session_loss.assert_not_called()\n\n    def test_partial_scope_is_aborted_once_before_replay(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n        self.prompt(commander)\n        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        self.assertNotIn(\"abort\", feature.executed)\n        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n\n    def test_failed_context_reset_does_not_loop(self):\n        commander, terminal, _feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander, \"interface\")\n        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n            self.prompt(commander, \"interface\")\n        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n\n    def test_session_loss_during_context_reset_resumes_after_login(self):\n        commander, terminal, feature = self.make_commander()\n        self.prompt(commander)\n        self.enter_interface(commander)\n        self.prompt(commander, \"interface\")\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        self.enter_interface(commander)\n        self.finish_interface(commander)\n        self.assertTrue(feature.completed)\n        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n\n    def test_cleanup_session_loss_is_bounded(self):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock())\n        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n        commander.register_cleanup(feature, CleanupAction(\n            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n        ))\n        commander.start([feature])\n        self.prompt(commander)\n        self.prompt(commander)  # Begin cleanup after the feature completes.\n        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.reconnect(commander)\n        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n\n    def test_newly_submitted_block_resets_retry_allowance(self):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock())\n        feature = StaticFeature(None, commander, \"two-blocks\", [\n            ConfigBlock(\"system global\", [\"set alias first\"]),\n            ConfigBlock(\"system global\", [\"set alias second\"]),\n        ])\n        commander.start([feature])\n        self.prompt(commander)\n        for _index in range(2):\n            self.prompt(commander, \"global\")\n            self.prompt(commander)  # Lost context: retry this block.\n            self.prompt(commander, \"global\")\n            self.prompt(commander, \"global\")\n            self.prompt(commander)  # End this block and start the next one.\n        self.assertTrue(feature.completed)\n        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 292,
        "totalLines": 292,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716561566,
      "end": 1793716561571
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_scope_errors.py"
}

Output

<path>/source/head/fortinet/tests/test_common_scope_errors.py</path>
<type>file</type>
<content>
1: """Scope commit failures are mandatory errors, including best-effort commands."""
2: 
3: import sys
4: import unittest
5: from pathlib import Path
6: from unittest.mock import MagicMock
7: 
8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
9: 
10: from fortinet.common.cli_commands import (  # noqa: E402
11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,
12: )
13: from fortinet.common.common import FOSCliState  # noqa: E402
14: from fortinet.common.features.base import Feature  # noqa: E402
15: from fortinet.common.fos_commander import FOSCommander  # noqa: E402
16: from fortinet.common.terminal import Data  # noqa: E402
17: 
18: 
19: class RecordingFeature(Feature):
20:     def __init__(self, commander, name, commands):
21:         super().__init__(None, commander, name)
22:         self.commands = commands
23:         self.executed = []
24: 
25:     def activate(self):
26:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))
27: 
28:     def on_command_executed(self, attempt, state):
29:         self.executed.append(attempt.spec.line)
30: 
31: 
32: class ScopeCommitFailureTests(unittest.TestCase):
33:     @staticmethod
34:     def prompt(commander, context=None, output=b""):
35:         scope = f" ({context})" if context else ""
36:         commander.on_state(FOSCliState.CMD_PROMPT, Data(
37:             output + f"fw{scope} #".encode()
38:         ))
39: 
40:     @staticmethod
41:     def writes(terminal):
42:         return [call.args[0] for call in terminal.write.call_args_list]
43: 
44:     def test_closing_failure_cannot_be_disabled_or_replayed(self):
45:         for close in ("next", "end"):
46:             for capture in (False, True):
47:                 for best_effort in (False, True):
48:                     with self.subTest(close=close, capture=capture, best_effort=best_effort):
49:                         terminal = MagicMock()
50:                         commander = FOSCommander(terminal, MagicMock(), best_effort)
51:                         feature = RecordingFeature(commander, "commit", [
52:                             CommandSpec(close, capture_output=capture, fail_on_error=False),
53:                             "set must-not-run 1",
54:                         ])
55:                         feature.on_context_loss = MagicMock()
56:                         following = RecordingFeature(commander, "following", ["get status"])
57:                         commander.start([feature, following])
58:                         self.prompt(commander, "port1")
59:                         # The failure code can span multiple serial reads.
60:                         for chunk in (b"Command fa", b"il. Return co", b"de -542.\r\n"):
61:                             data = Data(chunk)
62:                             commander.on_output(data)
63:                             self.assertTrue(data.discarded)
64:                         if best_effort:
65:                             self.prompt(commander, "interface")
66:                             self.assertEqual(self.writes(terminal), [close + "\r", "get status\r"])
67:                             self.assertEqual(commander.feature_errors[0][0], "commit")
68:                             self.assertIn("return code -542", commander.feature_errors[0][1])
69:                         else:
70:                             with self.assertRaisesRegex(RuntimeError, "return code -542"):
71:                                 self.prompt(commander, "interface")
72:                             self.assertEqual(self.writes(terminal), [close + "\r"])
73:                         feature.on_context_loss.assert_not_called()
74:                         self.assertEqual(feature.executed, [])
75:                         self.assertFalse(feature.completed)
76: 
77:     def test_closing_failure_with_same_prompt_still_ejects(self):
78:         for code in ("0", "7", "-61"):
79:             for suffix in ("", "."):
80:                 with self.subTest(code=code, suffix=suffix):
81:                     terminal = MagicMock()
82:                     commander = FOSCommander(terminal, MagicMock())
83:                     feature = RecordingFeature(commander, "commit", ["next", "end"])
84:                     commander.start([feature])
85:                     self.prompt(commander, "port1")
86:                     with self.assertRaisesRegex(RuntimeError, f"return code {code}"):
87:                         self.prompt(
88:                             commander, "port1",
89:                             f"  Command fail. Return code {code}{suffix}\r\n".encode(),
90:                         )
91:                     self.assertEqual(self.writes(terminal), ["next\r"])
92: 
93:     def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):
94:         for capture in (False, True):
95:             with self.subTest(capture=capture):
96:                 terminal = MagicMock()
97:                 commander = FOSCommander(terminal, MagicMock())
98:                 feature = RecordingFeature(commander, "configure", [
99:                     ConfigBlock("system interface", [EditBlock("port1", [
100:                         CommandSpec("set unsupported 1", capture_output=capture),
101:                     ])]),
102:                 ])
103:                 commander.start([feature])
104:                 self.prompt(commander)
105:                 self.prompt(commander, "interface")
106:                 self.prompt(commander, "port1")
107:                 self.prompt(commander, "port1", b"Command fail. Return code -61.\r\n")
108:                 self.assertEqual(self.writes(terminal)[-1], "next\r")
109:                 self.prompt(commander, "interface")
110:                 self.prompt(commander)
111:                 self.assertTrue(feature.completed)
112:                 self.assertTrue(commander.ready)
113:                 self.assertEqual(commander.feature_errors, ())
114: 
115:     def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):
116:         for best_effort in (False, True):
117:             with self.subTest(best_effort=best_effort):
118:                 terminal = MagicMock()
119:                 commander = FOSCommander(terminal, MagicMock(), best_effort)
120:                 feature = RecordingFeature(commander, "work", ["get initial"])
121:                 following = RecordingFeature(commander, "following", ["get status"])
122:                 commander.register_cleanup(feature, CleanupAction(
123:                     "close", CommandSequence("close", ["end"]),
124:                 ))
125:                 commander.start([feature, following])
126:                 self.prompt(commander)
127:                 self.prompt(commander)
128:                 self.assertEqual(self.writes(terminal)[-1], "end\r")
129:                 if best_effort:
130:                     self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
131:                     self.assertEqual(commander.feature_errors[0][0], "cleanup")
132:                     self.assertEqual(self.writes(terminal)[-1], "get status\r")
133:                 else:
134:                     with self.assertRaisesRegex(RuntimeError, "return code -5"):
135:                         self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
136:                     self.assertNotIn("get status\r", self.writes(terminal))
137: 
138:     def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):
139:         terminal = MagicMock()
140:         commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)
141:         feature = RecordingFeature(commander, "commit", [CommandSpec(
142:             "end", completion_states=(FOSCliState.CONFIRMATION,),
143:             expected_completion_state=FOSCliState.CMD_PROMPT,
144:         )])
145:         commander.start([feature])
146:         self.prompt(commander, "interface")
147:         with self.assertRaisesRegex(RuntimeError, "unexpected prompt"):
148:             commander.on_state(FOSCliState.CONFIRMATION, Data(b"Do you want to continue?"))
149:         self.assertEqual(self.writes(terminal), ["end\r"])
150:         self.assertFalse(feature.completed)
151: 
152: 
153: if __name__ == "__main__":
154:     unittest.main()

(End of file - total 154 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d6a6e2001QBeC11uNhjhusn",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d68fc6001YUuZT3OH6uecsd",
  "callID": "call_2b6762ab39b74c04ac39444b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_scope_errors.py"
    },
    "output": "<path>/source/head/fortinet/tests/test_common_scope_errors.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n2: \n3: import sys\n4: import unittest\n5: from pathlib import Path\n6: from unittest.mock import MagicMock\n7: \n8: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n9: \n10: from fortinet.common.cli_commands import (  # noqa: E402\n11:     CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n12: )\n13: from fortinet.common.common import FOSCliState  # noqa: E402\n14: from fortinet.common.features.base import Feature  # noqa: E402\n15: from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n16: from fortinet.common.terminal import Data  # noqa: E402\n17: \n18: \n19: class RecordingFeature(Feature):\n20:     def __init__(self, commander, name, commands):\n21:         super().__init__(None, commander, name)\n22:         self.commands = commands\n23:         self.executed = []\n24: \n25:     def activate(self):\n26:         self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n27: \n28:     def on_command_executed(self, attempt, state):\n29:         self.executed.append(attempt.spec.line)\n30: \n31: \n32: class ScopeCommitFailureTests(unittest.TestCase):\n33:     @staticmethod\n34:     def prompt(commander, context=None, output=b\"\"):\n35:         scope = f\" ({context})\" if context else \"\"\n36:         commander.on_state(FOSCliState.CMD_PROMPT, Data(\n37:             output + f\"fw{scope} #\".encode()\n38:         ))\n39: \n40:     @staticmethod\n41:     def writes(terminal):\n42:         return [call.args[0] for call in terminal.write.call_args_list]\n43: \n44:     def test_closing_failure_cannot_be_disabled_or_replayed(self):\n45:         for close in (\"next\", \"end\"):\n46:             for capture in (False, True):\n47:                 for best_effort in (False, True):\n48:                     with self.subTest(close=close, capture=capture, best_effort=best_effort):\n49:                         terminal = MagicMock()\n50:                         commander = FOSCommander(terminal, MagicMock(), best_effort)\n51:                         feature = RecordingFeature(commander, \"commit\", [\n52:                             CommandSpec(close, capture_output=capture, fail_on_error=False),\n53:                             \"set must-not-run 1\",\n54:                         ])\n55:                         feature.on_context_loss = MagicMock()\n56:                         following = RecordingFeature(commander, \"following\", [\"get status\"])\n57:                         commander.start([feature, following])\n58:                         self.prompt(commander, \"port1\")\n59:                         # The failure code can span multiple serial reads.\n60:                         for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n61:                             data = Data(chunk)\n62:                             commander.on_output(data)\n63:                             self.assertTrue(data.discarded)\n64:                         if best_effort:\n65:                             self.prompt(commander, \"interface\")\n66:                             self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n67:                             self.assertEqual(commander.feature_errors[0][0], \"commit\")\n68:                             self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n69:                         else:\n70:                             with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n71:                                 self.prompt(commander, \"interface\")\n72:                             self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n73:                         feature.on_context_loss.assert_not_called()\n74:                         self.assertEqual(feature.executed, [])\n75:                         self.assertFalse(feature.completed)\n76: \n77:     def test_closing_failure_with_same_prompt_still_ejects(self):\n78:         for code in (\"0\", \"7\", \"-61\"):\n79:             for suffix in (\"\", \".\"):\n80:                 with self.subTest(code=code, suffix=suffix):\n81:                     terminal = MagicMock()\n82:                     commander = FOSCommander(terminal, MagicMock())\n83:                     feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n84:                     commander.start([feature])\n85:                     self.prompt(commander, \"port1\")\n86:                     with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n87:                         self.prompt(\n88:                             commander, \"port1\",\n89:                             f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n90:                         )\n91:                     self.assertEqual(self.writes(terminal), [\"next\\r\"])\n92: \n93:     def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n94:         for capture in (False, True):\n95:             with self.subTest(capture=capture):\n96:                 terminal = MagicMock()\n97:                 commander = FOSCommander(terminal, MagicMock())\n98:                 feature = RecordingFeature(commander, \"configure\", [\n99:                     ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n100:                         CommandSpec(\"set unsupported 1\", capture_output=capture),\n101:                     ])]),\n102:                 ])\n103:                 commander.start([feature])\n104:                 self.prompt(commander)\n105:                 self.prompt(commander, \"interface\")\n106:                 self.prompt(commander, \"port1\")\n107:                 self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n108:                 self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n109:                 self.prompt(commander, \"interface\")\n110:                 self.prompt(commander)\n111:                 self.assertTrue(feature.completed)\n112:                 self.assertTrue(commander.ready)\n113:                 self.assertEqual(commander.feature_errors, ())\n114: \n115:     def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n116:         for best_effort in (False, True):\n117:             with self.subTest(best_effort=best_effort):\n118:                 terminal = MagicMock()\n119:                 commander = FOSCommander(terminal, MagicMock(), best_effort)\n120:                 feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n121:                 following = RecordingFeature(commander, \"following\", [\"get status\"])\n122:                 commander.register_cleanup(feature, CleanupAction(\n123:                     \"close\", CommandSequence(\"close\", [\"end\"]),\n124:                 ))\n125:                 commander.start([feature, following])\n126:                 self.prompt(commander)\n127:                 self.prompt(commander)\n128:                 self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n129:                 if best_effort:\n130:                     self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n131:                     self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n132:                     self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n133:                 else:\n134:                     with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n135:                         self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n136:                     self.assertNotIn(\"get status\\r\", self.writes(terminal))\n137: \n138:     def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n139:         terminal = MagicMock()\n140:         commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n141:         feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n142:             \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n143:             expected_completion_state=FOSCliState.CMD_PROMPT,\n144:         )])\n145:         commander.start([feature])\n146:         self.prompt(commander, \"interface\")\n147:         with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n148:             commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n149:         self.assertEqual(self.writes(terminal), [\"end\\r\"])\n150:         self.assertFalse(feature.completed)\n151: \n152: \n153: if __name__ == \"__main__\":\n154:     unittest.main()\n\n(End of file - total 154 lines)\n</content>",
    "title": "source/head/fortinet/tests/test_common_scope_errors.py",
    "metadata": {
      "preview": "\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_scope_errors.py",
        "text": "\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n\nimport sys\nimport unittest\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n\nfrom fortinet.common.cli_commands import (  # noqa: E402\n    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n)\nfrom fortinet.common.common import FOSCliState  # noqa: E402\nfrom fortinet.common.features.base import Feature  # noqa: E402\nfrom fortinet.common.fos_commander import FOSCommander  # noqa: E402\nfrom fortinet.common.terminal import Data  # noqa: E402\n\n\nclass RecordingFeature(Feature):\n    def __init__(self, commander, name, commands):\n        super().__init__(None, commander, name)\n        self.commands = commands\n        self.executed = []\n\n    def activate(self):\n        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n\n    def on_command_executed(self, attempt, state):\n        self.executed.append(attempt.spec.line)\n\n\nclass ScopeCommitFailureTests(unittest.TestCase):\n    @staticmethod\n    def prompt(commander, context=None, output=b\"\"):\n        scope = f\" ({context})\" if context else \"\"\n        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n            output + f\"fw{scope} #\".encode()\n        ))\n\n    @staticmethod\n    def writes(terminal):\n        return [call.args[0] for call in terminal.write.call_args_list]\n\n    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n        for close in (\"next\", \"end\"):\n            for capture in (False, True):\n                for best_effort in (False, True):\n                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n                        terminal = MagicMock()\n                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n                        feature = RecordingFeature(commander, \"commit\", [\n                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n                            \"set must-not-run 1\",\n                        ])\n                        feature.on_context_loss = MagicMock()\n                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n                        commander.start([feature, following])\n                        self.prompt(commander, \"port1\")\n                        # The failure code can span multiple serial reads.\n                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n                            data = Data(chunk)\n                            commander.on_output(data)\n                            self.assertTrue(data.discarded)\n                        if best_effort:\n                            self.prompt(commander, \"interface\")\n                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n                        else:\n                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n                                self.prompt(commander, \"interface\")\n                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n                        feature.on_context_loss.assert_not_called()\n                        self.assertEqual(feature.executed, [])\n                        self.assertFalse(feature.completed)\n\n    def test_closing_failure_with_same_prompt_still_ejects(self):\n        for code in (\"0\", \"7\", \"-61\"):\n            for suffix in (\"\", \".\"):\n                with self.subTest(code=code, suffix=suffix):\n                    terminal = MagicMock()\n                    commander = FOSCommander(terminal, MagicMock())\n                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n                    commander.start([feature])\n                    self.prompt(commander, \"port1\")\n                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n                        self.prompt(\n                            commander, \"port1\",\n                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n                        )\n                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n\n    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n        for capture in (False, True):\n            with self.subTest(capture=capture):\n                terminal = MagicMock()\n                commander = FOSCommander(terminal, MagicMock())\n                feature = RecordingFeature(commander, \"configure\", [\n                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n                    ])]),\n                ])\n                commander.start([feature])\n                self.prompt(commander)\n                self.prompt(commander, \"interface\")\n                self.prompt(commander, \"port1\")\n                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n                self.prompt(commander, \"interface\")\n                self.prompt(commander)\n                self.assertTrue(feature.completed)\n                self.assertTrue(commander.ready)\n                self.assertEqual(commander.feature_errors, ())\n\n    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n        for best_effort in (False, True):\n            with self.subTest(best_effort=best_effort):\n                terminal = MagicMock()\n                commander = FOSCommander(terminal, MagicMock(), best_effort)\n                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n                following = RecordingFeature(commander, \"following\", [\"get status\"])\n                commander.register_cleanup(feature, CleanupAction(\n                    \"close\", CommandSequence(\"close\", [\"end\"]),\n                ))\n                commander.start([feature, following])\n                self.prompt(commander)\n                self.prompt(commander)\n                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n                if best_effort:\n                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n                else:\n                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n\n    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n        terminal = MagicMock()\n        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n            expected_completion_state=FOSCliState.CMD_PROMPT,\n        )])\n        commander.start([feature])\n        self.prompt(commander, \"interface\")\n        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n        self.assertFalse(feature.completed)\n\n\nif __name__ == \"__main__\":\n    unittest.main()",
        "lineStart": 1,
        "lineEnd": 154,
        "totalLines": 154,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716561637,
      "end": 1793716561642
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d6a6eb001Hktl02TxRj6oM8",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d68fc6001YUuZT3OH6uecsd",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 40323,
    "input": 7767,
    "output": 78,
    "reasoning": 478,
    "cache": {
      "read": 32000,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d68fc6001YUuZT3OH6uecsd",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716555718,
    "completed": 1793716561646
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 40323,
    "input": 7767,
    "output": 78,
    "reasoning": 478,
    "cache": {
      "read": 32000,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 29
step-start
{
  "type": "step-start",
  "id": "prt_1a1d6af29001TeJEgwbeUAznEC",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6a6f5001olbbGFgBgts46C"
}
Reasoning
All three new test files fully read. Now the READMEs.
Now the two READMEs.
read · completed

Input

{
  "filePath": "/source/head/fortinet/fortigate/README.md"
}

Output

<path>/source/head/fortinet/fortigate/README.md</path>
<type>file</type>
<content>
1: # Fortinet FortiGate
2: 
3: Fortinet FortiGate/FortiOS support for vrnetlab and Containerlab.
4: 
5: The launcher supports recent FortiGate VM images, including FortiOS 8.0, and
6: similar Fortinet CLI families such as FortiProxy where the boot and prompt
7: patterns are compatible.
8: 
9: ## Build
10: 
11: Place one FortiOS `qcow2` image in this directory. The Makefile expects the
12: image name to use this format:
13: 
14: ```text
15: fortios-vX.Y.Z.qcow2
16: ```
17: 
18: Build the image:
19: 
20: ```bash
21: make docker-build-fortigate
22: ```
23: 
24: Run the image manually:
25: 
26: ```bash
27: make docker-run-fortigate
28: ```
29: 
30: ## Containerlab
31: 
32: Use `kind: fortinet_fortigate`.
33: 
34: ```yaml
35: name: fgt-lab
36: 
37: topology:
38:   nodes:
39:     fgt:
40:       kind: fortinet_fortigate
41:       image: vr-fortios:8.0.0
42:       enforce-startup-config: true
43:       startup-config: configs/fgt.conf
44:       license: licenses/appliance.lic
45:       dns:
46:         servers:
47:           - 1.1.1.1
48:           - 8.8.8.8
49:       credentials:
50:         username: admin
51:         password: admin
52:       env:
53:         CLAB_MGMT_PASSTHROUGH: "true"
54:         FTNT_DISK_SPECS: "10g,10g"
55:         FTNT_LICENSE_STATUS_TIMEOUT_SECONDS: "120"
56:         FTNT_LOG_LEVEL: "DEBUG"
57:         FTNT_NO_ENC_CONFIG: "false"
58:         FTNT_ONBOARDING: "false"
59:         UUID: "6c6323d5-0713-58eb-9458-4f8803a2cd93"
60: ```
61: 
62: ### Node Options
63: 
64: `startup-config` mounts a FortiOS config file that the launcher applies after
65: bootstrap, hostname setup, license handling, admin setup, and baseline config
66: capture. The file is available inside the container as
67: `/config/startup-config.cfg`.
68: 
69: `license` mounts a FortiGate VM license. The launcher expects it inside the
70: container as `/tftpboot/appliance.lic`, installs it with
71: `execute restore vmlicense tftp`, handles the reboot, and waits for license
72: status to leave `Pending`.
73: 
74: `credentials` sets the desired final administrator account. If omitted, the
75: final account is `admin` / `admin`. The bootstrap flow handles first-login
76: password change prompts and FortiOS versions that initially accept a blank
77: default password.
78: 
79: `enforce-startup-config: true` is recommended so Containerlab always mounts and
80: applies the intended startup config.
81: 
82: Containerlab's `dns.servers` setting configures the container resolver. During
83: bootstrap, the launcher uses its first two nameservers for FortiOS DNS unless
84: `FTNT_DNS_PRIMARY` or `FTNT_DNS_SECONDARY` overrides them. If the container has
85: no configured nameservers, the defaults are `1.1.1.1` and `8.8.8.8`.
86: 
87: ## Environment Variables
88: 
89: | Variable | Default | Values | Description |
90: | --- | --- | --- | --- |
91: | `CLAB_MGMT_PASSTHROUGH` | `true` | `true`, `false` | Selects management wiring. `true` uses tap/tc passthrough so the FortiGate management interface participates directly in the Containerlab management network. `false` uses a host-forwarded bridge inside the vrnetlab container. |
92: | `FTNT_DISK_SPECS` | unset | comma-separated `qemu-img create` sizes, for example `10g` or `10g,10g` | Adds extra virtio disks. One disk becomes the FortiGate log disk. Additional disks are formatted during bootstrap; the second disk is expected to become WAN optimization storage on FortiOS versions that support it. |
93: | `FTNT_DEBUG_FEATURE` | unset | feature name | Runs bootstrap only through the named feature, then skips later features. Public feature order: `image-info`, `product-validation`, `disk-format`, `admin`, `management`, `bootstrap-dns`, `fortiguard-hooks`, `setup-license`, `fortiguard-hooks-after-license`, `default-config`, `management-after-license`, `license-validation`, `fortitoken-provisioning`, `pki-certificates`, `management-vrf`, `capture-config`, `startup-config`. |
94: | `FTNT_DNS_PRIMARY` | first container nameserver, otherwise `1.1.1.1` | IPv4 address | Sets the primary FortiOS DNS server. |
95: | `FTNT_DNS_SECONDARY` | second container nameserver, otherwise `8.8.8.8` | IPv4 address | Sets the secondary FortiOS DNS server. |
96: | `FTNT_DNS_PROTOCOL` | `cleartext` | `cleartext`, `dot`, `doh` | Sets DNS over UDP/TCP 53, DNS over TLS 853, or DNS over HTTPS 443. FortiOS versions that do not support this setting may reject it; that command failure is ignored. |
97: | `FTNT_EXIT_ON_BOOTSTRAP_ERROR` | `true` | `true`, `false` | Stops the launcher with a nonzero exit status when a bootstrap feature raises an error. With `false`, a failed feature is skipped and later features continue when FortiOS is back at a command prompt. After a rejected desired-password login, the launcher always retries the last accepted credentials once for that login while retaining the desired credentials for subsequent logins. It does not replay an admin password change after FortiOS has committed it. Unrecoverable console or login errors leave the VM running, release the launcher's serial Telnet connection, and halt bootstrap for manual repair. Unresolved recovery or skipped features keep the VM unhealthy; a later successful login with the desired credentials clears a transient credential-recovery error. |
98: | `FTNT_HEALTHCHECK_STALL_SECONDS` | `90` | seconds | How long the Docker healthcheck probe waits for a launcher heartbeat before reporting failure. Only relevant for diagnostics; the launcher must stay responsive within this window. See [Container Healthcheck](#container-healthcheck). |
99: | `FTNT_HEARTBEAT_FILE` | `/healthbeat` | container path | File the launcher appends one byte to on every main-loop iteration; the healthcheck probe watches it to distinguish a slow bootstrap from a wedged launcher. |
100: | `FTNT_LOG_LICENSE_STATUS_OUTPUT` | `false` | `true`, `false` | When `true`, logs the first full `get system status` response captured for each distinct license status. Useful for diagnosing license-status parsing. |
101: | `FTNT_LICENSE_STATUS_TIMEOUT_SECONDS` | `120` | seconds | Maximum time to poll `get system status` while waiting for license validation. `Pending` is always retried; `Grace Period` is retried only when `FTNT_WAIT_FOR_VALID_LICENSE=true`. |
102: | `FTNT_LOG_LEVEL` | `DEBUG` | `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, or numeric Python log level | Sets launcher log verbosity. |
103: | `FTNT_NO_ENC_CONFIG` | `false` | `true`, `false` | When `true`, ignores ENC-only changes on entries that already exist in the baseline. New entries and entries with other changes retain their encrypted fields. |
104: | `FTNT_ONBOARDING` | `false` | `true`, `false` | When `true`, disables the HTTPS redirect and automatic-upgrade setup warning in the default FortiOS GUI configuration. |
105: | `FTNT_SKIP_PRODUCT_CHECK` | `false` | `true`, `false` | Skips validation that the image reports the expected product family and satisfies `FTNT_PRODUCT_VERSION`. General FortiOS version detection still runs during bootstrap. |
106: | `FTNT_WAIT_FOR_VALID_LICENSE` | `false` | `true`, `false` | When `true`, keeps polling while the license status is `Grace Period` and only accepts `Valid`. By default, `Grace Period` is accepted so bootstrap can continue. |
107: | `FTNT_PRODUCT_VERSION` | unset | `8`, `8.0`, `8.0.1`, `8.b278`, `8.0.b278`, `8.0.1.b278`, or an inclusive range such as `7.2-8.0.1` | Constrains the reported product version. A release prefix accepts that version line (`8` accepts 8.x; `8.0` accepts 8.0.x; `8.0.1` accepts builds for exactly 8.0.1). Add `.bNNN` to require an exact build on the selected line (`M.m.p.b#`); build numbers may be zero-padded to four digits, such as `.b0123`. Four numeric components such as `M.m.p.#` are invalid. An unset or empty value leaves version selection in automatic mode. |
108: | `FTNT_PKI_CA_CERTS` | unset | semicolon-separated `refname:path` PEM entries | Trusts CA certificates by typing the PEM into `config vpn certificate ca`. The object is named after the refname when given, otherwise the certificate CN. |
109: | `FTNT_PKI_LOCAL_CERTS` | unset | semicolon-separated `refname:key_path:cert_path` entries | Installs local certificate/private-key pairs, including the SSL deep-inspection CA pair, by typing the PEM contents into `config vpn certificate local`. Both files are required. The object is named after the refname when given, otherwise the certificate CN; use an empty refname (`:key_path:cert_path`) to imply the name. |
110: | `FTNT_PKI_LOCAL_CERT_PASS_FILES` | unset | semicolon-separated file paths | Optional password files whose contents are typed as `set password` for encrypted private keys, paired positionally with keyed `FTNT_PKI_LOCAL_CERTS` entries. |
111: | `FTNT_PKI_REMOTE_CERTS` | unset | semicolon-separated `refname:path` PEM entries | Installs remote peer certificates by typing the PEM into `config vpn certificate remote`. The object is named after the refname when given, otherwise the certificate CN. |
112: | `FTNT_PKI_CRLS` | unset | semicolon-separated `refname:path` CRL entries | Installs CRLs as base64 bodies in `config vpn certificate crl` when that tree is available. Older releases without a CRL config tree use `execute vpn certificate crl import tftp`. The object is named after the refname when given, otherwise the file basename. |
113: | `UUID` | random UUID | UUID string | Sets the QEMU VM UUID. If unset, vrnetlab generates a random UUID for the VM instance. |
114: 
115: The `FTNT_` names are the documented environment interface. Existing
116: environment variable names remain accepted during the compatibility period.
117: 
118: Containerlab also passes the usual vrnetlab launch arguments such as hostname,
119: username, password, and connection mode. For manual runs these are available as
120: launcher arguments:
121: 
122: ```text
123: --hostname
124: --username
125: --password
126: --connection-mode
127: ```
128: 
129: ## Management Modes
130: 
131: ### Passthrough Management
132: 
133: `CLAB_MGMT_PASSTHROUGH=true` is the default. The launcher creates a tap device
134: for `port1` and uses tc rules to redirect management traffic between the
135: FortiGate VM and the container management interface. TCP serial ports
136: `5000-5007` are passed through to the container instead of being redirected to
137: the VM management interface.
138: 
139: The TFTP server used for license installation runs in a dedicated namespace and
140: is reachable from the FortiGate through the management gateway address.
141: 
142: ### Host-Forwarded Management
143: 
144: `CLAB_MGMT_PASSTHROUGH=false` creates an internal `br-mgmt` bridge and configures
145: FortiGate `port1` with:
146: 
147: ```text
148: 172.31.255.30/30 via 172.31.255.29
149: 200::1/127 via 200::
150: ```
151: 
152: TCP traffic that enters the container, except the serial console on port `5000`,
153: is DNATed to the FortiGate management address. UDP traffic is also DNATed so
154: license TFTP can work.
155: 
156: If FortiOS later receives DHCP on the management interface, disable the
157: FortiGate default gateway only after adding a route back to the management
158: subnet. Disabling it first can cut off management access.
159: 
160: ## Startup Config
161: 
162: The startup config is applied line by line after the launcher has finished its
163: own bootstrap commands. Keep it as ordinary FortiOS CLI config:
164: 
165: ```text
166: config system global
167:     set alias "lab-fgt"
168: end
169: ```
170: 
171: The importer validates basic `config` / `edit` / `next` / `end` nesting and
172: fails startup on malformed structure or unterminated quoted strings. Single-
173: and double-quoted values can span lines. Newlines, whitespace, blank lines,
174: and scope keywords inside a quoted value are preserved. Each continued line
175: is sent only after the CLI's continuation prompt; the closing line must return
176: to a command prompt. An unexpected prompt follows the bootstrap error policy.
177: 
178: The bootstrap DNS servers selected from the container resolver or
179: `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config
180: application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS
181: variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup
182: config is skipped with a warning so it cannot override the launcher's DNS.
183: 
184: ## Default Startup Configuration
185: 
186: Before the user startup config is applied, the launcher leaves this baseline in
187: the node when management IPv4 is static. Values in angle brackets are derived
188: from Containerlab management settings and node credentials. With DHCP
189: management, the static `port1` and route `9999` configuration is omitted.
190: 
191: ```text
192: config system interface
193:     edit port1
194:         set mode static
195:         set ip <management-ipv4/prefix>
196:         set allowaccess ping https ssh http
197:         config ipv6                         # when management IPv6 is configured
198:             set ip6-mode static
199:             set ip6-address <management-ipv6/prefix>
200:             set ip6-allowaccess ping https ssh http
201:         end
202:     next
203: end
204: 
205: config system fortiguard
206:     set interface-select-method specify
207:     set interface port1
208:     set auto-join-forticloud disable
209: end
210: 
211: config router static
212:     edit 9999
213:         set gateway <management-ipv4-gateway>
214:         set device port1
215:     next
216: end
217: 
218: config router static6                       # when management IPv6 is configured
219:     edit 9999
220:         set gateway <management-ipv6-gateway>
221:         set device port1
222:     next
223: end
224: 
225: config system global
226:     set admin-scp enable
227:     set admin-https-redirect disable             # when FTNT_ONBOARDING=true
228:     set gui-auto-upgrade-setup-warning disable   # when FTNT_ONBOARDING=true
229:     set hostname <node-name>
230: end
231: 
232: config system password-policy
233:     set status disable
234: end
235: 
236: config system admin
237:     edit <username>                          # `admin` by default
238:         set accprofile super_admin
239:         set password <password>              # `admin` by default
240:     next
241: end
242: 
243: config system console
244:     set output more
245: end
246: ```
247: 
248: The DNS servers selected from the container resolver or
249: `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` are configured during bootstrap and
250: are not removed afterwards; they persist into the captured baseline and the
251: final configuration.
252: 
253: When a license is installed, the launcher reapplies management configuration
254: after the license reboot and attempts to place `port1` and route `9999` in VRF
255: 1. On FortiProxy, where `set vrf 1` is unsupported, route `9999` is narrowed to
256: the management gateway destination using the management address prefix; this
257: avoids overriding a lab default route.
258: 
259: The launcher captures this baseline before it imports the user startup config.
260: The startup config can override preceding baseline commands, except that the
261: launcher restores console pagination to `more` after import.
262: 
263: ## Licensing
264: 
265: When `/tftpboot/appliance.lic` exists, the launcher installs it during startup.
266: License installation may reboot the VM and may remove the active admin session
267: when the status changes to `VALID`; the launcher handles re-login and continues
268: bootstrap.
269: 
270: After installation, the launcher polls `get system status`. `Pending` is
271: retried until the status changes. By default, `Grace Period` is accepted so
272: bootstrap can continue; set `FTNT_WAIT_FOR_VALID_LICENSE=true` to keep polling
273: until the status is `Valid`. Other non-valid statuses fail validation
274: immediately. The default polling timeout is 2 minutes; set
275: `FTNT_LICENSE_STATUS_TIMEOUT_SECONDS` to change it.
276: 
277: ## PKI Certificates
278: 
279: Set the `FTNT_PKI_*` variables to install certificates, CAs, and CRLs at
280: bootstrap. All variables carry file paths only — the plugin stages the PEM
281: files and the launcher reads their contents; certificate, key, and password
282: bytes never travel through the environment.
283: 
284: ```yaml
285: envs:
286:   FTNT_PKI_CA_CERTS: "root:/lab/root-ca.pem;intermediate:/lab/intermediate.pem"
287:   FTNT_PKI_LOCAL_CERTS: "server:/lab/server.key:/lab/server.pem;dca:/lab/dca.key:/lab/dca.pem"
288:   FTNT_PKI_LOCAL_CERT_PASS_FILES: "/lab/server.pass"
289:   FTNT_PKI_REMOTE_CERTS: "peer:/lab/peer.pem"
290:   FTNT_PKI_CRLS: "issuer:/lab/issuer.crl"
291: ```
292: 
293: Entries are `;`-separated and always start with a refname field followed
294: by `:` (`refname:rest`). The refname names the FortiOS object; an empty
295: refname field implies the name — the certificate CN for certificates, the
296: file basename for CRLs. Local certificate entries require both a private key
297: and certificate. A bare `key_path:cert_path` without the leading refname field
298: is rejected; use `:key_path:cert_path` for CN-derived naming.
299: 
300: - `FTNT_PKI_CA_CERTS` and `FTNT_PKI_REMOTE_CERTS` entries are first typed into
301:   their respective `config vpn certificate` trees and named by refname or CN.
302: - `FTNT_PKI_LOCAL_CERTS` entries are typed into
303:   `config vpn certificate local` as quoted multi-line PEM values named by
304:   refname or CN. Every entry must supply its private key before its certificate.
305:   The same mechanism covers server certificates and the SSL deep-inspection CA
306:   pair.
307: - `FTNT_PKI_LOCAL_CERT_PASS_FILES` entries pair positionally with
308:   keyed `FTNT_PKI_LOCAL_CERTS` entries whose private keys are encrypted.
309: - `FTNT_PKI_CRLS` entries are installed as base64 bodies when the FortiOS
310:   version has a CRL config tree. On older versions without that tree, each CRL
311:   is staged under `/tftpboot/pki/` and installed with the TFTP import command.
312: 
313: If config installation fails for a CA, remote certificate, or CRL, that object
314: is staged under `/tftpboot/pki/` and retried with `execute vpn certificate ...
315: import tftp`. A successful fallback logs a warning. A failed fallback aborts
316: bootstrap with an error. Local certificate/key pairs cannot use this fallback
317: because FortiOS TFTP import does not accept the configured separate key and
318: certificate files; their config failure therefore aborts bootstrap directly.
319: 
320: Certificates are installed after the factory baseline is captured and before
321: the startup config applies, so startup config can reference installed
322: certificate names. Duplicate object names within one category keep the last
323: entry and log a warning. Missing files abort startup with an error naming
324: the variable and path. Not supported: SCEP/EST/CMP enrollment, HSM
325: certificates, OCSP
326: servers, inline base64 certificate values, certificate generation, and
327: ssl-ssh-profile wiring.
328: 
329: ## Extra Disks
330: 
331: Set `FTNT_DISK_SPECS` to add disks:
332: 
333: ```yaml
334: env:
335:   FTNT_DISK_SPECS: "10g,10g"
336: ```
337: 
338: This creates `empty1.qcow2`, `empty2.qcow2`, and so on, and attaches them as
339: virtio drives. FortiOS normally formats the first additional disk as log
340: storage. The launcher formats remaining configured disks during bootstrap.
341: 
342: Expected FortiOS storage usage for common test cases:
343: 
344: ```text
345: FTNT_DISK_SPECS unset      -> no configured storage usage
346: FTNT_DISK_SPECS="10g"     -> order 1 usage log
347: FTNT_DISK_SPECS="10g,10g" -> order 1 usage log, order 2 usage wanopt
348: ```
349: 
350: Disk formatting during bootstrap adds roughly a minute per additional
351: drive to the time the container stays `starting`. The healthcheck absorbs
352: this automatically — see [Container Healthcheck](#container-healthcheck).
353: 
354: ## Container Healthcheck
355: 
356: The image's `HEALTHCHECK` runs `/fos_healthcheck.py`, which replaces the
357: plain `/health`-file check from upstream vrnetlab. The problem it solves:
358: FortiOS bootstrap takes several minutes, and with Docker's default probe
359: timing (30 s interval, 3 retries) the container flapped
360: `starting -> unhealthy (1 starting) -> healthy (0 running)` purely
361: because the third probe landed before bootstrap finished.
362: 
363: How it works:
364: 
365: - The launcher appends one byte to `/healthbeat` on every main-loop
366:   iteration.
367: - While `/health` still says the VM is starting, the probe blocks,
368:   waiting for those heartbeat bytes. Docker keeps a container in
369:   `starting` while a probe run is in flight, so a slow-but-progressing
370:   bootstrap holds `starting` for as long as it likes — no fixed start
371:   period to size against disk count or platform.
372: - If no new heartbeat byte arrives for `FTNT_HEALTHCHECK_STALL_SECONDS`
373:   (default 90 s), the launcher is wedged: the probe exits 1 and Docker
374:   marks the container unhealthy after `--retries` strikes.
375: - Once bootstrap has completed, the probe defers to the classic check:
376:   `0 running` exits 0 immediately, `1 VM failed - restarting` exits 1,
377:   so a VM that dies after startup still goes unhealthy on the normal
378:   probe schedule (~90 s).
379: 
380: ## Saving Config
381: 
382: Ask the launcher to capture the current FortiOS config by writing a request
383: to `/get-config` inside a running container:
384: 
385: ```bash
386: docker exec -i clab-<lab>-<node> sh -c \
387:   'cat > /get-config.incoming && mv /get-config.incoming /get-config' <<<'{"id": "abc123"}'
388: ```
389: 
390: The trigger carries a request id (1–128 characters of
391: `A-Za-z0-9._-`; clients use a uuid4 hex). The launcher consumes the trigger
392: and answers with one JSON status record **per request id**, written
393: atomically under:
394: 
395: ```text
396: /config/get-config.status.d/<id>.json
397: ```
398: 
399: with body `{"id": "<id>", "status": "pending" | "success" | "busy" | "error",
400: "output"?: "<config filename>", "error"?: "<message>"}`. A waiting client
401: polls its own record only, so a previous capture's output can never satisfy
402: a new request. Statuses:
403: 
404: - `pending` — accepted; the capture is queued or running.
405: - `success` — the config below is freshly rendered and stable to read.
406: - `busy` — the CLI scheduler was mid-capture; the trigger was still
407:   consumed. Re-issue with a **fresh id** (the busy request was rejected).
408: - `error` — the request was rejected (unusable id, stale output could not
409:   be removed, serial reconnect failed); `error` carries the reason.
410: 
411: A trigger created *or modified* between watcher polls is a new request, so
412: a client that re-writes the trigger while an earlier capture runs gets its
413: own record instead of a silently dropped request. A trigger consumed by a
414: stale earlier request is left in place when it already carries a newer id
415: (compare-before-unlink), so the newer client is still served.
416: 
417: An empty trigger — a human `touch /get-config` — still requests a capture;
418: it is answered under a generated id, so watch the directory listing of
419: `/config/get-config.status.d/` for the record. Records older than 120
420: seconds are swept when a new request is accepted.
421: 
422: The launcher reconnects to the serial console, runs `show`, compares the result
423: with the baseline captured before startup config application, and writes the
424: changed config to:
425: 
426: ```text
427: /config/current.conf
428: ```
429: 
430: The serial connection is closed after capture so the console remains available
431: for external use. Capture requests standard console output from the launcher;
432: when the VM originally used pagination, it is restored after capture and before
433: the user startup configuration is applied.
434: 
435: The comparison parses `config` and `edit` blocks into a tree. Unchanged entries
436: are skipped. New entries are written completely, including encrypted fields.
437: For an existing entry, any non-encrypted body change causes its complete current
438: subtree to be written, including encrypted fields and any nested `config`
439: blocks. Parent `config` / `edit` ancestry is retained so `current.conf` remains
440: replayable.
441: 
442: FortiOS may emit a different `ENC` representation for a protected value on
443: each `show`, even when the underlying secret has not changed. The capture
444: cannot distinguish that regenerated representation from a real password or
445: secret change, because the value is opaque. There is therefore a tradeoff:
446: 
447: - By default, ENC-only differences count as changes. This preserves a real
448:   secret-only update on an existing entry, but regenerated ENC values can cause
449:   an otherwise unchanged entry to be included in `current.conf`.
450: - Set `FTNT_NO_ENC_CONFIG=true` to ignore ENC-only differences on existing
451:   entries. This avoids captures caused only by regenerated ENC values, but a
452:   real secret-only update on an existing entry will not be captured.
453: 
454: This setting affects only ENC-only differences on entries already present in
455: the baseline. New entries are still written completely, and an existing entry
456: with any other body change is still written with its current encrypted fields.
457: 
458: ## Boot Features
459: 
460: The FortiOS launcher uses a CLI finite-state machine rather than fixed sleeps.
461: User-visible behavior includes:
462: 
463: - detection of login, password, forced password-change, rejected credentials,
464:   welcome banner, reboot, shutdown, and command prompts
465: - buffered prompt matching for fragmented serial output
466: - hostname update and prompt-pattern update during bootstrap
467: - `admin-scp` enabled for configuration backup support
468: - default credential handling across FortiOS 6.4, 7.x, and 8.x behavior
469: - password-policy failure surfaced as a startup error
470: - bootstrap feature failures stop startup by default; with
471:   `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, failures at a command prompt are logged
472:   and that feature is skipped while remaining features continue. A rejected
473:   desired-password login always gets one retry with the last accepted
474:   credentials for that login; the desired credentials remain active for later
475:   logins. A committed admin password-change block is not replayed after logout.
476:   Errors that leave the console outside a command prompt or reject both
477:   credentials still halt bootstrap, release the launcher's serial Telnet
478:   connection, and leave the VM for manual repair. A credential-recovery error
479:   remains until the desired credentials later authenticate successfully. A
480:   run with unresolved credential recovery or skipped features is not reported
481:   healthy.
482: - explicit failure if no `qcow2` image is present
483: - full serial output logging at debug level
484: 
485: ## Tested Versions
486: 
487: Tested with:
488: 
489: - FortiGate 8.0.0 build 0167 GA debug image
490: - FortiGate 7.6.6 build 3652 GA debug image
491: - FortiGate 7.4.12 build 2902 GA
492: - FortiGate 7.0.19 build 0696 GA
493: - FortiGate 6.4.16 build 2098 GA
494: - FortiProxy 7.6.6 build 1628 GA
495: - FortiProxy 7.4.13 build 0722 GA debug image
496: - FortiProxy 7.2.16 build 0465 GA
497: - FortiProxy 7.0.23 build 0222 GA

(End of file - total 497 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d6afc0001NODMq9e7osFNC7",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6a6f5001olbbGFgBgts46C",
  "callID": "call_cc80b609b3be40cb850b7d25",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/fortigate/README.md"
    },
    "output": "<path>/source/head/fortinet/fortigate/README.md</path>\n<type>file</type>\n<content>\n1: # Fortinet FortiGate\n2: \n3: Fortinet FortiGate/FortiOS support for vrnetlab and Containerlab.\n4: \n5: The launcher supports recent FortiGate VM images, including FortiOS 8.0, and\n6: similar Fortinet CLI families such as FortiProxy where the boot and prompt\n7: patterns are compatible.\n8: \n9: ## Build\n10: \n11: Place one FortiOS `qcow2` image in this directory. The Makefile expects the\n12: image name to use this format:\n13: \n14: ```text\n15: fortios-vX.Y.Z.qcow2\n16: ```\n17: \n18: Build the image:\n19: \n20: ```bash\n21: make docker-build-fortigate\n22: ```\n23: \n24: Run the image manually:\n25: \n26: ```bash\n27: make docker-run-fortigate\n28: ```\n29: \n30: ## Containerlab\n31: \n32: Use `kind: fortinet_fortigate`.\n33: \n34: ```yaml\n35: name: fgt-lab\n36: \n37: topology:\n38:   nodes:\n39:     fgt:\n40:       kind: fortinet_fortigate\n41:       image: vr-fortios:8.0.0\n42:       enforce-startup-config: true\n43:       startup-config: configs/fgt.conf\n44:       license: licenses/appliance.lic\n45:       dns:\n46:         servers:\n47:           - 1.1.1.1\n48:           - 8.8.8.8\n49:       credentials:\n50:         username: admin\n51:         password: admin\n52:       env:\n53:         CLAB_MGMT_PASSTHROUGH: \"true\"\n54:         FTNT_DISK_SPECS: \"10g,10g\"\n55:         FTNT_LICENSE_STATUS_TIMEOUT_SECONDS: \"120\"\n56:         FTNT_LOG_LEVEL: \"DEBUG\"\n57:         FTNT_NO_ENC_CONFIG: \"false\"\n58:         FTNT_ONBOARDING: \"false\"\n59:         UUID: \"6c6323d5-0713-58eb-9458-4f8803a2cd93\"\n60: ```\n61: \n62: ### Node Options\n63: \n64: `startup-config` mounts a FortiOS config file that the launcher applies after\n65: bootstrap, hostname setup, license handling, admin setup, and baseline config\n66: capture. The file is available inside the container as\n67: `/config/startup-config.cfg`.\n68: \n69: `license` mounts a FortiGate VM license. The launcher expects it inside the\n70: container as `/tftpboot/appliance.lic`, installs it with\n71: `execute restore vmlicense tftp`, handles the reboot, and waits for license\n72: status to leave `Pending`.\n73: \n74: `credentials` sets the desired final administrator account. If omitted, the\n75: final account is `admin` / `admin`. The bootstrap flow handles first-login\n76: password change prompts and FortiOS versions that initially accept a blank\n77: default password.\n78: \n79: `enforce-startup-config: true` is recommended so Containerlab always mounts and\n80: applies the intended startup config.\n81: \n82: Containerlab's `dns.servers` setting configures the container resolver. During\n83: bootstrap, the launcher uses its first two nameservers for FortiOS DNS unless\n84: `FTNT_DNS_PRIMARY` or `FTNT_DNS_SECONDARY` overrides them. If the container has\n85: no configured nameservers, the defaults are `1.1.1.1` and `8.8.8.8`.\n86: \n87: ## Environment Variables\n88: \n89: | Variable | Default | Values | Description |\n90: | --- | --- | --- | --- |\n91: | `CLAB_MGMT_PASSTHROUGH` | `true` | `true`, `false` | Selects management wiring. `true` uses tap/tc passthrough so the FortiGate management interface participates directly in the Containerlab management network. `false` uses a host-forwarded bridge inside the vrnetlab container. |\n92: | `FTNT_DISK_SPECS` | unset | comma-separated `qemu-img create` sizes, for example `10g` or `10g,10g` | Adds extra virtio disks. One disk becomes the FortiGate log disk. Additional disks are formatted during bootstrap; the second disk is expected to become WAN optimization storage on FortiOS versions that support it. |\n93: | `FTNT_DEBUG_FEATURE` | unset | feature name | Runs bootstrap only through the named feature, then skips later features. Public feature order: `image-info`, `product-validation`, `disk-format`, `admin`, `management`, `bootstrap-dns`, `fortiguard-hooks`, `setup-license`, `fortiguard-hooks-after-license`, `default-config`, `management-after-license`, `license-validation`, `fortitoken-provisioning`, `pki-certificates`, `management-vrf`, `capture-config`, `startup-config`. |\n94: | `FTNT_DNS_PRIMARY` | first container nameserver, otherwise `1.1.1.1` | IPv4 address | Sets the primary FortiOS DNS server. |\n95: | `FTNT_DNS_SECONDARY` | second container nameserver, otherwise `8.8.8.8` | IPv4 address | Sets the secondary FortiOS DNS server. |\n96: | `FTNT_DNS_PROTOCOL` | `cleartext` | `cleartext`, `dot`, `doh` | Sets DNS over UDP/TCP 53, DNS over TLS 853, or DNS over HTTPS 443. FortiOS versions that do not support this setting may reject it; that command failure is ignored. |\n97: | `FTNT_EXIT_ON_BOOTSTRAP_ERROR` | `true` | `true`, `false` | Stops the launcher with a nonzero exit status when a bootstrap feature raises an error. With `false`, a failed feature is skipped and later features continue when FortiOS is back at a command prompt. After a rejected desired-password login, the launcher always retries the last accepted credentials once for that login while retaining the desired credentials for subsequent logins. It does not replay an admin password change after FortiOS has committed it. Unrecoverable console or login errors leave the VM running, release the launcher's serial Telnet connection, and halt bootstrap for manual repair. Unresolved recovery or skipped features keep the VM unhealthy; a later successful login with the desired credentials clears a transient credential-recovery error. |\n98: | `FTNT_HEALTHCHECK_STALL_SECONDS` | `90` | seconds | How long the Docker healthcheck probe waits for a launcher heartbeat before reporting failure. Only relevant for diagnostics; the launcher must stay responsive within this window. See [Container Healthcheck](#container-healthcheck). |\n99: | `FTNT_HEARTBEAT_FILE` | `/healthbeat` | container path | File the launcher appends one byte to on every main-loop iteration; the healthcheck probe watches it to distinguish a slow bootstrap from a wedged launcher. |\n100: | `FTNT_LOG_LICENSE_STATUS_OUTPUT` | `false` | `true`, `false` | When `true`, logs the first full `get system status` response captured for each distinct license status. Useful for diagnosing license-status parsing. |\n101: | `FTNT_LICENSE_STATUS_TIMEOUT_SECONDS` | `120` | seconds | Maximum time to poll `get system status` while waiting for license validation. `Pending` is always retried; `Grace Period` is retried only when `FTNT_WAIT_FOR_VALID_LICENSE=true`. |\n102: | `FTNT_LOG_LEVEL` | `DEBUG` | `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, or numeric Python log level | Sets launcher log verbosity. |\n103: | `FTNT_NO_ENC_CONFIG` | `false` | `true`, `false` | When `true`, ignores ENC-only changes on entries that already exist in the baseline. New entries and entries with other changes retain their encrypted fields. |\n104: | `FTNT_ONBOARDING` | `false` | `true`, `false` | When `true`, disables the HTTPS redirect and automatic-upgrade setup warning in the default FortiOS GUI configuration. |\n105: | `FTNT_SKIP_PRODUCT_CHECK` | `false` | `true`, `false` | Skips validation that the image reports the expected product family and satisfies `FTNT_PRODUCT_VERSION`. General FortiOS version detection still runs during bootstrap. |\n106: | `FTNT_WAIT_FOR_VALID_LICENSE` | `false` | `true`, `false` | When `true`, keeps polling while the license status is `Grace Period` and only accepts `Valid`. By default, `Grace Period` is accepted so bootstrap can continue. |\n107: | `FTNT_PRODUCT_VERSION` | unset | `8`, `8.0`, `8.0.1`, `8.b278`, `8.0.b278`, `8.0.1.b278`, or an inclusive range such as `7.2-8.0.1` | Constrains the reported product version. A release prefix accepts that version line (`8` accepts 8.x; `8.0` accepts 8.0.x; `8.0.1` accepts builds for exactly 8.0.1). Add `.bNNN` to require an exact build on the selected line (`M.m.p.b#`); build numbers may be zero-padded to four digits, such as `.b0123`. Four numeric components such as `M.m.p.#` are invalid. An unset or empty value leaves version selection in automatic mode. |\n108: | `FTNT_PKI_CA_CERTS` | unset | semicolon-separated `refname:path` PEM entries | Trusts CA certificates by typing the PEM into `config vpn certificate ca`. The object is named after the refname when given, otherwise the certificate CN. |\n109: | `FTNT_PKI_LOCAL_CERTS` | unset | semicolon-separated `refname:key_path:cert_path` entries | Installs local certificate/private-key pairs, including the SSL deep-inspection CA pair, by typing the PEM contents into `config vpn certificate local`. Both files are required. The object is named after the refname when given, otherwise the certificate CN; use an empty refname (`:key_path:cert_path`) to imply the name. |\n110: | `FTNT_PKI_LOCAL_CERT_PASS_FILES` | unset | semicolon-separated file paths | Optional password files whose contents are typed as `set password` for encrypted private keys, paired positionally with keyed `FTNT_PKI_LOCAL_CERTS` entries. |\n111: | `FTNT_PKI_REMOTE_CERTS` | unset | semicolon-separated `refname:path` PEM entries | Installs remote peer certificates by typing the PEM into `config vpn certificate remote`. The object is named after the refname when given, otherwise the certificate CN. |\n112: | `FTNT_PKI_CRLS` | unset | semicolon-separated `refname:path` CRL entries | Installs CRLs as base64 bodies in `config vpn certificate crl` when that tree is available. Older releases without a CRL config tree use `execute vpn certificate crl import tftp`. The object is named after the refname when given, otherwise the file basename. |\n113: | `UUID` | random UUID | UUID string | Sets the QEMU VM UUID. If unset, vrnetlab generates a random UUID for the VM instance. |\n114: \n115: The `FTNT_` names are the documented environment interface. Existing\n116: environment variable names remain accepted during the compatibility period.\n117: \n118: Containerlab also passes the usual vrnetlab launch arguments such as hostname,\n119: username, password, and connection mode. For manual runs these are available as\n120: launcher arguments:\n121: \n122: ```text\n123: --hostname\n124: --username\n125: --password\n126: --connection-mode\n127: ```\n128: \n129: ## Management Modes\n130: \n131: ### Passthrough Management\n132: \n133: `CLAB_MGMT_PASSTHROUGH=true` is the default. The launcher creates a tap device\n134: for `port1` and uses tc rules to redirect management traffic between the\n135: FortiGate VM and the container management interface. TCP serial ports\n136: `5000-5007` are passed through to the container instead of being redirected to\n137: the VM management interface.\n138: \n139: The TFTP server used for license installation runs in a dedicated namespace and\n140: is reachable from the FortiGate through the management gateway address.\n141: \n142: ### Host-Forwarded Management\n143: \n144: `CLAB_MGMT_PASSTHROUGH=false` creates an internal `br-mgmt` bridge and configures\n145: FortiGate `port1` with:\n146: \n147: ```text\n148: 172.31.255.30/30 via 172.31.255.29\n149: 200::1/127 via 200::\n150: ```\n151: \n152: TCP traffic that enters the container, except the serial console on port `5000`,\n153: is DNATed to the FortiGate management address. UDP traffic is also DNATed so\n154: license TFTP can work.\n155: \n156: If FortiOS later receives DHCP on the management interface, disable the\n157: FortiGate default gateway only after adding a route back to the management\n158: subnet. Disabling it first can cut off management access.\n159: \n160: ## Startup Config\n161: \n162: The startup config is applied line by line after the launcher has finished its\n163: own bootstrap commands. Keep it as ordinary FortiOS CLI config:\n164: \n165: ```text\n166: config system global\n167:     set alias \"lab-fgt\"\n168: end\n169: ```\n170: \n171: The importer validates basic `config` / `edit` / `next` / `end` nesting and\n172: fails startup on malformed structure or unterminated quoted strings. Single-\n173: and double-quoted values can span lines. Newlines, whitespace, blank lines,\n174: and scope keywords inside a quoted value are preserved. Each continued line\n175: is sent only after the CLI's continuation prompt; the closing line must return\n176: to a command prompt. An unexpected prompt follows the bootstrap error policy.\n177: \n178: The bootstrap DNS servers selected from the container resolver or\n179: `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n180: application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n181: variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\n182: config is skipped with a warning so it cannot override the launcher's DNS.\n183: \n184: ## Default Startup Configuration\n185: \n186: Before the user startup config is applied, the launcher leaves this baseline in\n187: the node when management IPv4 is static. Values in angle brackets are derived\n188: from Containerlab management settings and node credentials. With DHCP\n189: management, the static `port1` and route `9999` configuration is omitted.\n190: \n191: ```text\n192: config system interface\n193:     edit port1\n194:         set mode static\n195:         set ip <management-ipv4/prefix>\n196:         set allowaccess ping https ssh http\n197:         config ipv6                         # when management IPv6 is configured\n198:             set ip6-mode static\n199:             set ip6-address <management-ipv6/prefix>\n200:             set ip6-allowaccess ping https ssh http\n201:         end\n202:     next\n203: end\n204: \n205: config system fortiguard\n206:     set interface-select-method specify\n207:     set interface port1\n208:     set auto-join-forticloud disable\n209: end\n210: \n211: config router static\n212:     edit 9999\n213:         set gateway <management-ipv4-gateway>\n214:         set device port1\n215:     next\n216: end\n217: \n218: config router static6                       # when management IPv6 is configured\n219:     edit 9999\n220:         set gateway <management-ipv6-gateway>\n221:         set device port1\n222:     next\n223: end\n224: \n225: config system global\n226:     set admin-scp enable\n227:     set admin-https-redirect disable             # when FTNT_ONBOARDING=true\n228:     set gui-auto-upgrade-setup-warning disable   # when FTNT_ONBOARDING=true\n229:     set hostname <node-name>\n230: end\n231: \n232: config system password-policy\n233:     set status disable\n234: end\n235: \n236: config system admin\n237:     edit <username>                          # `admin` by default\n238:         set accprofile super_admin\n239:         set password <password>              # `admin` by default\n240:     next\n241: end\n242: \n243: config system console\n244:     set output more\n245: end\n246: ```\n247: \n248: The DNS servers selected from the container resolver or\n249: `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` are configured during bootstrap and\n250: are not removed afterwards; they persist into the captured baseline and the\n251: final configuration.\n252: \n253: When a license is installed, the launcher reapplies management configuration\n254: after the license reboot and attempts to place `port1` and route `9999` in VRF\n255: 1. On FortiProxy, where `set vrf 1` is unsupported, route `9999` is narrowed to\n256: the management gateway destination using the management address prefix; this\n257: avoids overriding a lab default route.\n258: \n259: The launcher captures this baseline before it imports the user startup config.\n260: The startup config can override preceding baseline commands, except that the\n261: launcher restores console pagination to `more` after import.\n262: \n263: ## Licensing\n264: \n265: When `/tftpboot/appliance.lic` exists, the launcher installs it during startup.\n266: License installation may reboot the VM and may remove the active admin session\n267: when the status changes to `VALID`; the launcher handles re-login and continues\n268: bootstrap.\n269: \n270: After installation, the launcher polls `get system status`. `Pending` is\n271: retried until the status changes. By default, `Grace Period` is accepted so\n272: bootstrap can continue; set `FTNT_WAIT_FOR_VALID_LICENSE=true` to keep polling\n273: until the status is `Valid`. Other non-valid statuses fail validation\n274: immediately. The default polling timeout is 2 minutes; set\n275: `FTNT_LICENSE_STATUS_TIMEOUT_SECONDS` to change it.\n276: \n277: ## PKI Certificates\n278: \n279: Set the `FTNT_PKI_*` variables to install certificates, CAs, and CRLs at\n280: bootstrap. All variables carry file paths only — the plugin stages the PEM\n281: files and the launcher reads their contents; certificate, key, and password\n282: bytes never travel through the environment.\n283: \n284: ```yaml\n285: envs:\n286:   FTNT_PKI_CA_CERTS: \"root:/lab/root-ca.pem;intermediate:/lab/intermediate.pem\"\n287:   FTNT_PKI_LOCAL_CERTS: \"server:/lab/server.key:/lab/server.pem;dca:/lab/dca.key:/lab/dca.pem\"\n288:   FTNT_PKI_LOCAL_CERT_PASS_FILES: \"/lab/server.pass\"\n289:   FTNT_PKI_REMOTE_CERTS: \"peer:/lab/peer.pem\"\n290:   FTNT_PKI_CRLS: \"issuer:/lab/issuer.crl\"\n291: ```\n292: \n293: Entries are `;`-separated and always start with a refname field followed\n294: by `:` (`refname:rest`). The refname names the FortiOS object; an empty\n295: refname field implies the name — the certificate CN for certificates, the\n296: file basename for CRLs. Local certificate entries require both a private key\n297: and certificate. A bare `key_path:cert_path` without the leading refname field\n298: is rejected; use `:key_path:cert_path` for CN-derived naming.\n299: \n300: - `FTNT_PKI_CA_CERTS` and `FTNT_PKI_REMOTE_CERTS` entries are first typed into\n301:   their respective `config vpn certificate` trees and named by refname or CN.\n302: - `FTNT_PKI_LOCAL_CERTS` entries are typed into\n303:   `config vpn certificate local` as quoted multi-line PEM values named by\n304:   refname or CN. Every entry must supply its private key before its certificate.\n305:   The same mechanism covers server certificates and the SSL deep-inspection CA\n306:   pair.\n307: - `FTNT_PKI_LOCAL_CERT_PASS_FILES` entries pair positionally with\n308:   keyed `FTNT_PKI_LOCAL_CERTS` entries whose private keys are encrypted.\n309: - `FTNT_PKI_CRLS` entries are installed as base64 bodies when the FortiOS\n310:   version has a CRL config tree. On older versions without that tree, each CRL\n311:   is staged under `/tftpboot/pki/` and installed with the TFTP import command.\n312: \n313: If config installation fails for a CA, remote certificate, or CRL, that object\n314: is staged under `/tftpboot/pki/` and retried with `execute vpn certificate ...\n315: import tftp`. A successful fallback logs a warning. A failed fallback aborts\n316: bootstrap with an error. Local certificate/key pairs cannot use this fallback\n317: because FortiOS TFTP import does not accept the configured separate key and\n318: certificate files; their config failure therefore aborts bootstrap directly.\n319: \n320: Certificates are installed after the factory baseline is captured and before\n321: the startup config applies, so startup config can reference installed\n322: certificate names. Duplicate object names within one category keep the last\n323: entry and log a warning. Missing files abort startup with an error naming\n324: the variable and path. Not supported: SCEP/EST/CMP enrollment, HSM\n325: certificates, OCSP\n326: servers, inline base64 certificate values, certificate generation, and\n327: ssl-ssh-profile wiring.\n328: \n329: ## Extra Disks\n330: \n331: Set `FTNT_DISK_SPECS` to add disks:\n332: \n333: ```yaml\n334: env:\n335:   FTNT_DISK_SPECS: \"10g,10g\"\n336: ```\n337: \n338: This creates `empty1.qcow2`, `empty2.qcow2`, and so on, and attaches them as\n339: virtio drives. FortiOS normally formats the first additional disk as log\n340: storage. The launcher formats remaining configured disks during bootstrap.\n341: \n342: Expected FortiOS storage usage for common test cases:\n343: \n344: ```text\n345: FTNT_DISK_SPECS unset      -> no configured storage usage\n346: FTNT_DISK_SPECS=\"10g\"     -> order 1 usage log\n347: FTNT_DISK_SPECS=\"10g,10g\" -> order 1 usage log, order 2 usage wanopt\n348: ```\n349: \n350: Disk formatting during bootstrap adds roughly a minute per additional\n351: drive to the time the container stays `starting`. The healthcheck absorbs\n352: this automatically — see [Container Healthcheck](#container-healthcheck).\n353: \n354: ## Container Healthcheck\n355: \n356: The image's `HEALTHCHECK` runs `/fos_healthcheck.py`, which replaces the\n357: plain `/health`-file check from upstream vrnetlab. The problem it solves:\n358: FortiOS bootstrap takes several minutes, and with Docker's default probe\n359: timing (30 s interval, 3 retries) the container flapped\n360: `starting -> unhealthy (1 starting) -> healthy (0 running)` purely\n361: because the third probe landed before bootstrap finished.\n362: \n363: How it works:\n364: \n365: - The launcher appends one byte to `/healthbeat` on every main-loop\n366:   iteration.\n367: - While `/health` still says the VM is starting, the probe blocks,\n368:   waiting for those heartbeat bytes. Docker keeps a container in\n369:   `starting` while a probe run is in flight, so a slow-but-progressing\n370:   bootstrap holds `starting` for as long as it likes — no fixed start\n371:   period to size against disk count or platform.\n372: - If no new heartbeat byte arrives for `FTNT_HEALTHCHECK_STALL_SECONDS`\n373:   (default 90 s), the launcher is wedged: the probe exits 1 and Docker\n374:   marks the container unhealthy after `--retries` strikes.\n375: - Once bootstrap has completed, the probe defers to the classic check:\n376:   `0 running` exits 0 immediately, `1 VM failed - restarting` exits 1,\n377:   so a VM that dies after startup still goes unhealthy on the normal\n378:   probe schedule (~90 s).\n379: \n380: ## Saving Config\n381: \n382: Ask the launcher to capture the current FortiOS config by writing a request\n383: to `/get-config` inside a running container:\n384: \n385: ```bash\n386: docker exec -i clab-<lab>-<node> sh -c \\\n387:   'cat > /get-config.incoming && mv /get-config.incoming /get-config' <<<'{\"id\": \"abc123\"}'\n388: ```\n389: \n390: The trigger carries a request id (1–128 characters of\n391: `A-Za-z0-9._-`; clients use a uuid4 hex). The launcher consumes the trigger\n392: and answers with one JSON status record **per request id**, written\n393: atomically under:\n394: \n395: ```text\n396: /config/get-config.status.d/<id>.json\n397: ```\n398: \n399: with body `{\"id\": \"<id>\", \"status\": \"pending\" | \"success\" | \"busy\" | \"error\",\n400: \"output\"?: \"<config filename>\", \"error\"?: \"<message>\"}`. A waiting client\n401: polls its own record only, so a previous capture's output can never satisfy\n402: a new request. Statuses:\n403: \n404: - `pending` — accepted; the capture is queued or running.\n405: - `success` — the config below is freshly rendered and stable to read.\n406: - `busy` — the CLI scheduler was mid-capture; the trigger was still\n407:   consumed. Re-issue with a **fresh id** (the busy request was rejected).\n408: - `error` — the request was rejected (unusable id, stale output could not\n409:   be removed, serial reconnect failed); `error` carries the reason.\n410: \n411: A trigger created *or modified* between watcher polls is a new request, so\n412: a client that re-writes the trigger while an earlier capture runs gets its\n413: own record instead of a silently dropped request. A trigger consumed by a\n414: stale earlier request is left in place when it already carries a newer id\n415: (compare-before-unlink), so the newer client is still served.\n416: \n417: An empty trigger — a human `touch /get-config` — still requests a capture;\n418: it is answered under a generated id, so watch the directory listing of\n419: `/config/get-config.status.d/` for the record. Records older than 120\n420: seconds are swept when a new request is accepted.\n421: \n422: The launcher reconnects to the serial console, runs `show`, compares the result\n423: with the baseline captured before startup config application, and writes the\n424: changed config to:\n425: \n426: ```text\n427: /config/current.conf\n428: ```\n429: \n430: The serial connection is closed after capture so the console remains available\n431: for external use. Capture requests standard console output from the launcher;\n432: when the VM originally used pagination, it is restored after capture and before\n433: the user startup configuration is applied.\n434: \n435: The comparison parses `config` and `edit` blocks into a tree. Unchanged entries\n436: are skipped. New entries are written completely, including encrypted fields.\n437: For an existing entry, any non-encrypted body change causes its complete current\n438: subtree to be written, including encrypted fields and any nested `config`\n439: blocks. Parent `config` / `edit` ancestry is retained so `current.conf` remains\n440: replayable.\n441: \n442: FortiOS may emit a different `ENC` representation for a protected value on\n443: each `show`, even when the underlying secret has not changed. The capture\n444: cannot distinguish that regenerated representation from a real password or\n445: secret change, because the value is opaque. There is therefore a tradeoff:\n446: \n447: - By default, ENC-only differences count as changes. This preserves a real\n448:   secret-only update on an existing entry, but regenerated ENC values can cause\n449:   an otherwise unchanged entry to be included in `current.conf`.\n450: - Set `FTNT_NO_ENC_CONFIG=true` to ignore ENC-only differences on existing\n451:   entries. This avoids captures caused only by regenerated ENC values, but a\n452:   real secret-only update on an existing entry will not be captured.\n453: \n454: This setting affects only ENC-only differences on entries already present in\n455: the baseline. New entries are still written completely, and an existing entry\n456: with any other body change is still written with its current encrypted fields.\n457: \n458: ## Boot Features\n459: \n460: The FortiOS launcher uses a CLI finite-state machine rather than fixed sleeps.\n461: User-visible behavior includes:\n462: \n463: - detection of login, password, forced password-change, rejected credentials,\n464:   welcome banner, reboot, shutdown, and command prompts\n465: - buffered prompt matching for fragmented serial output\n466: - hostname update and prompt-pattern update during bootstrap\n467: - `admin-scp` enabled for configuration backup support\n468: - default credential handling across FortiOS 6.4, 7.x, and 8.x behavior\n469: - password-policy failure surfaced as a startup error\n470: - bootstrap feature failures stop startup by default; with\n471:   `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, failures at a command prompt are logged\n472:   and that feature is skipped while remaining features continue. A rejected\n473:   desired-password login always gets one retry with the last accepted\n474:   credentials for that login; the desired credentials remain active for later\n475:   logins. A committed admin password-change block is not replayed after logout.\n476:   Errors that leave the console outside a command prompt or reject both\n477:   credentials still halt bootstrap, release the launcher's serial Telnet\n478:   connection, and leave the VM for manual repair. A credential-recovery error\n479:   remains until the desired credentials later authenticate successfully. A\n480:   run with unresolved credential recovery or skipped features is not reported\n481:   healthy.\n482: - explicit failure if no `qcow2` image is present\n483: - full serial output logging at debug level\n484: \n485: ## Tested Versions\n486: \n487: Tested with:\n488: \n489: - FortiGate 8.0.0 build 0167 GA debug image\n490: - FortiGate 7.6.6 build 3652 GA debug image\n491: - FortiGate 7.4.12 build 2902 GA\n492: - FortiGate 7.0.19 build 0696 GA\n493: - FortiGate 6.4.16 build 2098 GA\n494: - FortiProxy 7.6.6 build 1628 GA\n495: - FortiProxy 7.4.13 build 0722 GA debug image\n496: - FortiProxy 7.2.16 build 0465 GA\n497: - FortiProxy 7.0.23 build 0222 GA\n\n(End of file - total 497 lines)\n</content>",
    "title": "source/head/fortinet/fortigate/README.md",
    "metadata": {
      "preview": "# Fortinet FortiGate\n\nFortinet FortiGate/FortiOS support for vrnetlab and Containerlab.\n\nThe launcher supports recent FortiGate VM images, including FortiOS 8.0, and\nsimilar Fortinet CLI families such as FortiProxy where the boot and prompt\npatterns are compatible.\n\n## Build\n\nPlace one FortiOS `qcow2` image in this directory. The Makefile expects the\nimage name to use this format:\n\n```text\nfortios-vX.Y.Z.qcow2\n```\n\nBuild the image:\n\n```bash",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/fortigate/README.md",
        "text": "# Fortinet FortiGate\n\nFortinet FortiGate/FortiOS support for vrnetlab and Containerlab.\n\nThe launcher supports recent FortiGate VM images, including FortiOS 8.0, and\nsimilar Fortinet CLI families such as FortiProxy where the boot and prompt\npatterns are compatible.\n\n## Build\n\nPlace one FortiOS `qcow2` image in this directory. The Makefile expects the\nimage name to use this format:\n\n```text\nfortios-vX.Y.Z.qcow2\n```\n\nBuild the image:\n\n```bash\nmake docker-build-fortigate\n```\n\nRun the image manually:\n\n```bash\nmake docker-run-fortigate\n```\n\n## Containerlab\n\nUse `kind: fortinet_fortigate`.\n\n```yaml\nname: fgt-lab\n\ntopology:\n  nodes:\n    fgt:\n      kind: fortinet_fortigate\n      image: vr-fortios:8.0.0\n      enforce-startup-config: true\n      startup-config: configs/fgt.conf\n      license: licenses/appliance.lic\n      dns:\n        servers:\n          - 1.1.1.1\n          - 8.8.8.8\n      credentials:\n        username: admin\n        password: admin\n      env:\n        CLAB_MGMT_PASSTHROUGH: \"true\"\n        FTNT_DISK_SPECS: \"10g,10g\"\n        FTNT_LICENSE_STATUS_TIMEOUT_SECONDS: \"120\"\n        FTNT_LOG_LEVEL: \"DEBUG\"\n        FTNT_NO_ENC_CONFIG: \"false\"\n        FTNT_ONBOARDING: \"false\"\n        UUID: \"6c6323d5-0713-58eb-9458-4f8803a2cd93\"\n```\n\n### Node Options\n\n`startup-config` mounts a FortiOS config file that the launcher applies after\nbootstrap, hostname setup, license handling, admin setup, and baseline config\ncapture. The file is available inside the container as\n`/config/startup-config.cfg`.\n\n`license` mounts a FortiGate VM license. The launcher expects it inside the\ncontainer as `/tftpboot/appliance.lic`, installs it with\n`execute restore vmlicense tftp`, handles the reboot, and waits for license\nstatus to leave `Pending`.\n\n`credentials` sets the desired final administrator account. If omitted, the\nfinal account is `admin` / `admin`. The bootstrap flow handles first-login\npassword change prompts and FortiOS versions that initially accept a blank\ndefault password.\n\n`enforce-startup-config: true` is recommended so Containerlab always mounts and\napplies the intended startup config.\n\nContainerlab's `dns.servers` setting configures the container resolver. During\nbootstrap, the launcher uses its first two nameservers for FortiOS DNS unless\n`FTNT_DNS_PRIMARY` or `FTNT_DNS_SECONDARY` overrides them. If the container has\nno configured nameservers, the defaults are `1.1.1.1` and `8.8.8.8`.\n\n## Environment Variables\n\n| Variable | Default | Values | Description |\n| --- | --- | --- | --- |\n| `CLAB_MGMT_PASSTHROUGH` | `true` | `true`, `false` | Selects management wiring. `true` uses tap/tc passthrough so the FortiGate management interface participates directly in the Containerlab management network. `false` uses a host-forwarded bridge inside the vrnetlab container. |\n| `FTNT_DISK_SPECS` | unset | comma-separated `qemu-img create` sizes, for example `10g` or `10g,10g` | Adds extra virtio disks. One disk becomes the FortiGate log disk. Additional disks are formatted during bootstrap; the second disk is expected to become WAN optimization storage on FortiOS versions that support it. |\n| `FTNT_DEBUG_FEATURE` | unset | feature name | Runs bootstrap only through the named feature, then skips later features. Public feature order: `image-info`, `product-validation`, `disk-format`, `admin`, `management`, `bootstrap-dns`, `fortiguard-hooks`, `setup-license`, `fortiguard-hooks-after-license`, `default-config`, `management-after-license`, `license-validation`, `fortitoken-provisioning`, `pki-certificates`, `management-vrf`, `capture-config`, `startup-config`. |\n| `FTNT_DNS_PRIMARY` | first container nameserver, otherwise `1.1.1.1` | IPv4 address | Sets the primary FortiOS DNS server. |\n| `FTNT_DNS_SECONDARY` | second container nameserver, otherwise `8.8.8.8` | IPv4 address | Sets the secondary FortiOS DNS server. |\n| `FTNT_DNS_PROTOCOL` | `cleartext` | `cleartext`, `dot`, `doh` | Sets DNS over UDP/TCP 53, DNS over TLS 853, or DNS over HTTPS 443. FortiOS versions that do not support this setting may reject it; that command failure is ignored. |\n| `FTNT_EXIT_ON_BOOTSTRAP_ERROR` | `true` | `true`, `false` | Stops the launcher with a nonzero exit status when a bootstrap feature raises an error. With `false`, a failed feature is skipped and later features continue when FortiOS is back at a command prompt. After a rejected desired-password login, the launcher always retries the last accepted credentials once for that login while retaining the desired credentials for subsequent logins. It does not replay an admin password change after FortiOS has committed it. Unrecoverable console or login errors leave the VM running, release the launcher's serial Telnet connection, and halt bootstrap for manual repair. Unresolved recovery or skipped features keep the VM unhealthy; a later successful login with the desired credentials clears a transient credential-recovery error. |\n| `FTNT_HEALTHCHECK_STALL_SECONDS` | `90` | seconds | How long the Docker healthcheck probe waits for a launcher heartbeat before reporting failure. Only relevant for diagnostics; the launcher must stay responsive within this window. See [Container Healthcheck](#container-healthcheck). |\n| `FTNT_HEARTBEAT_FILE` | `/healthbeat` | container path | File the launcher appends one byte to on every main-loop iteration; the healthcheck probe watches it to distinguish a slow bootstrap from a wedged launcher. |\n| `FTNT_LOG_LICENSE_STATUS_OUTPUT` | `false` | `true`, `false` | When `true`, logs the first full `get system status` response captured for each distinct license status. Useful for diagnosing license-status parsing. |\n| `FTNT_LICENSE_STATUS_TIMEOUT_SECONDS` | `120` | seconds | Maximum time to poll `get system status` while waiting for license validation. `Pending` is always retried; `Grace Period` is retried only when `FTNT_WAIT_FOR_VALID_LICENSE=true`. |\n| `FTNT_LOG_LEVEL` | `DEBUG` | `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, or numeric Python log level | Sets launcher log verbosity. |\n| `FTNT_NO_ENC_CONFIG` | `false` | `true`, `false` | When `true`, ignores ENC-only changes on entries that already exist in the baseline. New entries and entries with other changes retain their encrypted fields. |\n| `FTNT_ONBOARDING` | `false` | `true`, `false` | When `true`, disables the HTTPS redirect and automatic-upgrade setup warning in the default FortiOS GUI configuration. |\n| `FTNT_SKIP_PRODUCT_CHECK` | `false` | `true`, `false` | Skips validation that the image reports the expected product family and satisfies `FTNT_PRODUCT_VERSION`. General FortiOS version detection still runs during bootstrap. |\n| `FTNT_WAIT_FOR_VALID_LICENSE` | `false` | `true`, `false` | When `true`, keeps polling while the license status is `Grace Period` and only accepts `Valid`. By default, `Grace Period` is accepted so bootstrap can continue. |\n| `FTNT_PRODUCT_VERSION` | unset | `8`, `8.0`, `8.0.1`, `8.b278`, `8.0.b278`, `8.0.1.b278`, or an inclusive range such as `7.2-8.0.1` | Constrains the reported product version. A release prefix accepts that version line (`8` accepts 8.x; `8.0` accepts 8.0.x; `8.0.1` accepts builds for exactly 8.0.1). Add `.bNNN` to require an exact build on the selected line (`M.m.p.b#`); build numbers may be zero-padded to four digits, such as `.b0123`. Four numeric components such as `M.m.p.#` are invalid. An unset or empty value leaves version selection in automatic mode. |\n| `FTNT_PKI_CA_CERTS` | unset | semicolon-separated `refname:path` PEM entries | Trusts CA certificates by typing the PEM into `config vpn certificate ca`. The object is named after the refname when given, otherwise the certificate CN. |\n| `FTNT_PKI_LOCAL_CERTS` | unset | semicolon-separated `refname:key_path:cert_path` entries | Installs local certificate/private-key pairs, including the SSL deep-inspection CA pair, by typing the PEM contents into `config vpn certificate local`. Both files are required. The object is named after the refname when given, otherwise the certificate CN; use an empty refname (`:key_path:cert_path`) to imply the name. |\n| `FTNT_PKI_LOCAL_CERT_PASS_FILES` | unset | semicolon-separated file paths | Optional password files whose contents are typed as `set password` for encrypted private keys, paired positionally with keyed `FTNT_PKI_LOCAL_CERTS` entries. |\n| `FTNT_PKI_REMOTE_CERTS` | unset | semicolon-separated `refname:path` PEM entries | Installs remote peer certificates by typing the PEM into `config vpn certificate remote`. The object is named after the refname when given, otherwise the certificate CN. |\n| `FTNT_PKI_CRLS` | unset | semicolon-separated `refname:path` CRL entries | Installs CRLs as base64 bodies in `config vpn certificate crl` when that tree is available. Older releases without a CRL config tree use `execute vpn certificate crl import tftp`. The object is named after the refname when given, otherwise the file basename. |\n| `UUID` | random UUID | UUID string | Sets the QEMU VM UUID. If unset, vrnetlab generates a random UUID for the VM instance. |\n\nThe `FTNT_` names are the documented environment interface. Existing\nenvironment variable names remain accepted during the compatibility period.\n\nContainerlab also passes the usual vrnetlab launch arguments such as hostname,\nusername, password, and connection mode. For manual runs these are available as\nlauncher arguments:\n\n```text\n--hostname\n--username\n--password\n--connection-mode\n```\n\n## Management Modes\n\n### Passthrough Management\n\n`CLAB_MGMT_PASSTHROUGH=true` is the default. The launcher creates a tap device\nfor `port1` and uses tc rules to redirect management traffic between the\nFortiGate VM and the container management interface. TCP serial ports\n`5000-5007` are passed through to the container instead of being redirected to\nthe VM management interface.\n\nThe TFTP server used for license installation runs in a dedicated namespace and\nis reachable from the FortiGate through the management gateway address.\n\n### Host-Forwarded Management\n\n`CLAB_MGMT_PASSTHROUGH=false` creates an internal `br-mgmt` bridge and configures\nFortiGate `port1` with:\n\n```text\n172.31.255.30/30 via 172.31.255.29\n200::1/127 via 200::\n```\n\nTCP traffic that enters the container, except the serial console on port `5000`,\nis DNATed to the FortiGate management address. UDP traffic is also DNATed so\nlicense TFTP can work.\n\nIf FortiOS later receives DHCP on the management interface, disable the\nFortiGate default gateway only after adding a route back to the management\nsubnet. Disabling it first can cut off management access.\n\n## Startup Config\n\nThe startup config is applied line by line after the launcher has finished its\nown bootstrap commands. Keep it as ordinary FortiOS CLI config:\n\n```text\nconfig system global\n    set alias \"lab-fgt\"\nend\n```\n\nThe importer validates basic `config` / `edit` / `next` / `end` nesting and\nfails startup on malformed structure or unterminated quoted strings. Single-\nand double-quoted values can span lines. Newlines, whitespace, blank lines,\nand scope keywords inside a quoted value are preserved. Each continued line\nis sent only after the CLI's continuation prompt; the closing line must return\nto a command prompt. An unexpected prompt follows the bootstrap error policy.\n\nThe bootstrap DNS servers selected from the container resolver or\n`FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\napplication. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\nvariable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\nconfig is skipped with a warning so it cannot override the launcher's DNS.\n\n## Default Startup Configuration\n\nBefore the user startup config is applied, the launcher leaves this baseline in\nthe node when management IPv4 is static. Values in angle brackets are derived\nfrom Containerlab management settings and node credentials. With DHCP\nmanagement, the static `port1` and route `9999` configuration is omitted.\n\n```text\nconfig system interface\n    edit port1\n        set mode static\n        set ip <management-ipv4/prefix>\n        set allowaccess ping https ssh http\n        config ipv6                         # when management IPv6 is configured\n            set ip6-mode static\n            set ip6-address <management-ipv6/prefix>\n            set ip6-allowaccess ping https ssh http\n        end\n    next\nend\n\nconfig system fortiguard\n    set interface-select-method specify\n    set interface port1\n    set auto-join-forticloud disable\nend\n\nconfig router static\n    edit 9999\n        set gateway <management-ipv4-gateway>\n        set device port1\n    next\nend\n\nconfig router static6                       # when management IPv6 is configured\n    edit 9999\n        set gateway <management-ipv6-gateway>\n        set device port1\n    next\nend\n\nconfig system global\n    set admin-scp enable\n    set admin-https-redirect disable             # when FTNT_ONBOARDING=true\n    set gui-auto-upgrade-setup-warning disable   # when FTNT_ONBOARDING=true\n    set hostname <node-name>\nend\n\nconfig system password-policy\n    set status disable\nend\n\nconfig system admin\n    edit <username>                          # `admin` by default\n        set accprofile super_admin\n        set password <password>              # `admin` by default\n    next\nend\n\nconfig system console\n    set output more\nend\n```\n\nThe DNS servers selected from the container resolver or\n`FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` are configured during bootstrap and\nare not removed afterwards; they persist into the captured baseline and the\nfinal configuration.\n\nWhen a license is installed, the launcher reapplies management configuration\nafter the license reboot and attempts to place `port1` and route `9999` in VRF\n1. On FortiProxy, where `set vrf 1` is unsupported, route `9999` is narrowed to\nthe management gateway destination using the management address prefix; this\navoids overriding a lab default route.\n\nThe launcher captures this baseline before it imports the user startup config.\nThe startup config can override preceding baseline commands, except that the\nlauncher restores console pagination to `more` after import.\n\n## Licensing\n\nWhen `/tftpboot/appliance.lic` exists, the launcher installs it during startup.\nLicense installation may reboot the VM and may remove the active admin session\nwhen the status changes to `VALID`; the launcher handles re-login and continues\nbootstrap.\n\nAfter installation, the launcher polls `get system status`. `Pending` is\nretried until the status changes. By default, `Grace Period` is accepted so\nbootstrap can continue; set `FTNT_WAIT_FOR_VALID_LICENSE=true` to keep polling\nuntil the status is `Valid`. Other non-valid statuses fail validation\nimmediately. The default polling timeout is 2 minutes; set\n`FTNT_LICENSE_STATUS_TIMEOUT_SECONDS` to change it.\n\n## PKI Certificates\n\nSet the `FTNT_PKI_*` variables to install certificates, CAs, and CRLs at\nbootstrap. All variables carry file paths only — the plugin stages the PEM\nfiles and the launcher reads their contents; certificate, key, and password\nbytes never travel through the environment.\n\n```yaml\nenvs:\n  FTNT_PKI_CA_CERTS: \"root:/lab/root-ca.pem;intermediate:/lab/intermediate.pem\"\n  FTNT_PKI_LOCAL_CERTS: \"server:/lab/server.key:/lab/server.pem;dca:/lab/dca.key:/lab/dca.pem\"\n  FTNT_PKI_LOCAL_CERT_PASS_FILES: \"/lab/server.pass\"\n  FTNT_PKI_REMOTE_CERTS: \"peer:/lab/peer.pem\"\n  FTNT_PKI_CRLS: \"issuer:/lab/issuer.crl\"\n```\n\nEntries are `;`-separated and always start with a refname field followed\nby `:` (`refname:rest`). The refname names the FortiOS object; an empty\nrefname field implies the name — the certificate CN for certificates, the\nfile basename for CRLs. Local certificate entries require both a private key\nand certificate. A bare `key_path:cert_path` without the leading refname field\nis rejected; use `:key_path:cert_path` for CN-derived naming.\n\n- `FTNT_PKI_CA_CERTS` and `FTNT_PKI_REMOTE_CERTS` entries are first typed into\n  their respective `config vpn certificate` trees and named by refname or CN.\n- `FTNT_PKI_LOCAL_CERTS` entries are typed into\n  `config vpn certificate local` as quoted multi-line PEM values named by\n  refname or CN. Every entry must supply its private key before its certificate.\n  The same mechanism covers server certificates and the SSL deep-inspection CA\n  pair.\n- `FTNT_PKI_LOCAL_CERT_PASS_FILES` entries pair positionally with\n  keyed `FTNT_PKI_LOCAL_CERTS` entries whose private keys are encrypted.\n- `FTNT_PKI_CRLS` entries are installed as base64 bodies when the FortiOS\n  version has a CRL config tree. On older versions without that tree, each CRL\n  is staged under `/tftpboot/pki/` and installed with the TFTP import command.\n\nIf config installation fails for a CA, remote certificate, or CRL, that object\nis staged under `/tftpboot/pki/` and retried with `execute vpn certificate ...\nimport tftp`. A successful fallback logs a warning. A failed fallback aborts\nbootstrap with an error. Local certificate/key pairs cannot use this fallback\nbecause FortiOS TFTP import does not accept the configured separate key and\ncertificate files; their config failure therefore aborts bootstrap directly.\n\nCertificates are installed after the factory baseline is captured and before\nthe startup config applies, so startup config can reference installed\ncertificate names. Duplicate object names within one category keep the last\nentry and log a warning. Missing files abort startup with an error naming\nthe variable and path. Not supported: SCEP/EST/CMP enrollment, HSM\ncertificates, OCSP\nservers, inline base64 certificate values, certificate generation, and\nssl-ssh-profile wiring.\n\n## Extra Disks\n\nSet `FTNT_DISK_SPECS` to add disks:\n\n```yaml\nenv:\n  FTNT_DISK_SPECS: \"10g,10g\"\n```\n\nThis creates `empty1.qcow2`, `empty2.qcow2`, and so on, and attaches them as\nvirtio drives. FortiOS normally formats the first additional disk as log\nstorage. The launcher formats remaining configured disks during bootstrap.\n\nExpected FortiOS storage usage for common test cases:\n\n```text\nFTNT_DISK_SPECS unset      -> no configured storage usage\nFTNT_DISK_SPECS=\"10g\"     -> order 1 usage log\nFTNT_DISK_SPECS=\"10g,10g\" -> order 1 usage log, order 2 usage wanopt\n```\n\nDisk formatting during bootstrap adds roughly a minute per additional\ndrive to the time the container stays `starting`. The healthcheck absorbs\nthis automatically — see [Container Healthcheck](#container-healthcheck).\n\n## Container Healthcheck\n\nThe image's `HEALTHCHECK` runs `/fos_healthcheck.py`, which replaces the\nplain `/health`-file check from upstream vrnetlab. The problem it solves:\nFortiOS bootstrap takes several minutes, and with Docker's default probe\ntiming (30 s interval, 3 retries) the container flapped\n`starting -> unhealthy (1 starting) -> healthy (0 running)` purely\nbecause the third probe landed before bootstrap finished.\n\nHow it works:\n\n- The launcher appends one byte to `/healthbeat` on every main-loop\n  iteration.\n- While `/health` still says the VM is starting, the probe blocks,\n  waiting for those heartbeat bytes. Docker keeps a container in\n  `starting` while a probe run is in flight, so a slow-but-progressing\n  bootstrap holds `starting` for as long as it likes — no fixed start\n  period to size against disk count or platform.\n- If no new heartbeat byte arrives for `FTNT_HEALTHCHECK_STALL_SECONDS`\n  (default 90 s), the launcher is wedged: the probe exits 1 and Docker\n  marks the container unhealthy after `--retries` strikes.\n- Once bootstrap has completed, the probe defers to the classic check:\n  `0 running` exits 0 immediately, `1 VM failed - restarting` exits 1,\n  so a VM that dies after startup still goes unhealthy on the normal\n  probe schedule (~90 s).\n\n## Saving Config\n\nAsk the launcher to capture the current FortiOS config by writing a request\nto `/get-config` inside a running container:\n\n```bash\ndocker exec -i clab-<lab>-<node> sh -c \\\n  'cat > /get-config.incoming && mv /get-config.incoming /get-config' <<<'{\"id\": \"abc123\"}'\n```\n\nThe trigger carries a request id (1–128 characters of\n`A-Za-z0-9._-`; clients use a uuid4 hex). The launcher consumes the trigger\nand answers with one JSON status record **per request id**, written\natomically under:\n\n```text\n/config/get-config.status.d/<id>.json\n```\n\nwith body `{\"id\": \"<id>\", \"status\": \"pending\" | \"success\" | \"busy\" | \"error\",\n\"output\"?: \"<config filename>\", \"error\"?: \"<message>\"}`. A waiting client\npolls its own record only, so a previous capture's output can never satisfy\na new request. Statuses:\n\n- `pending` — accepted; the capture is queued or running.\n- `success` — the config below is freshly rendered and stable to read.\n- `busy` — the CLI scheduler was mid-capture; the trigger was still\n  consumed. Re-issue with a **fresh id** (the busy request was rejected).\n- `error` — the request was rejected (unusable id, stale output could not\n  be removed, serial reconnect failed); `error` carries the reason.\n\nA trigger created *or modified* between watcher polls is a new request, so\na client that re-writes the trigger while an earlier capture runs gets its\nown record instead of a silently dropped request. A trigger consumed by a\nstale earlier request is left in place when it already carries a newer id\n(compare-before-unlink), so the newer client is still served.\n\nAn empty trigger — a human `touch /get-config` — still requests a capture;\nit is answered under a generated id, so watch the directory listing of\n`/config/get-config.status.d/` for the record. Records older than 120\nseconds are swept when a new request is accepted.\n\nThe launcher reconnects to the serial console, runs `show`, compares the result\nwith the baseline captured before startup config application, and writes the\nchanged config to:\n\n```text\n/config/current.conf\n```\n\nThe serial connection is closed after capture so the console remains available\nfor external use. Capture requests standard console output from the launcher;\nwhen the VM originally used pagination, it is restored after capture and before\nthe user startup configuration is applied.\n\nThe comparison parses `config` and `edit` blocks into a tree. Unchanged entries\nare skipped. New entries are written completely, including encrypted fields.\nFor an existing entry, any non-encrypted body change causes its complete current\nsubtree to be written, including encrypted fields and any nested `config`\nblocks. Parent `config` / `edit` ancestry is retained so `current.conf` remains\nreplayable.\n\nFortiOS may emit a different `ENC` representation for a protected value on\neach `show`, even when the underlying secret has not changed. The capture\ncannot distinguish that regenerated representation from a real password or\nsecret change, because the value is opaque. There is therefore a tradeoff:\n\n- By default, ENC-only differences count as changes. This preserves a real\n  secret-only update on an existing entry, but regenerated ENC values can cause\n  an otherwise unchanged entry to be included in `current.conf`.\n- Set `FTNT_NO_ENC_CONFIG=true` to ignore ENC-only differences on existing\n  entries. This avoids captures caused only by regenerated ENC values, but a\n  real secret-only update on an existing entry will not be captured.\n\nThis setting affects only ENC-only differences on entries already present in\nthe baseline. New entries are still written completely, and an existing entry\nwith any other body change is still written with its current encrypted fields.\n\n## Boot Features\n\nThe FortiOS launcher uses a CLI finite-state machine rather than fixed sleeps.\nUser-visible behavior includes:\n\n- detection of login, password, forced password-change, rejected credentials,\n  welcome banner, reboot, shutdown, and command prompts\n- buffered prompt matching for fragmented serial output\n- hostname update and prompt-pattern update during bootstrap\n- `admin-scp` enabled for configuration backup support\n- default credential handling across FortiOS 6.4, 7.x, and 8.x behavior\n- password-policy failure surfaced as a startup error\n- bootstrap feature failures stop startup by default; with\n  `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, failures at a command prompt are logged\n  and that feature is skipped while remaining features continue. A rejected\n  desired-password login always gets one retry with the last accepted\n  credentials for that login; the desired credentials remain active for later\n  logins. A committed admin password-change block is not replayed after logout.\n  Errors that leave the console outside a command prompt or reject both\n  credentials still halt bootstrap, release the launcher's serial Telnet\n  connection, and leave the VM for manual repair. A credential-recovery error\n  remains until the desired credentials later authenticate successfully. A\n  run with unresolved credential recovery or skipped features is not reported\n  healthy.\n- explicit failure if no `qcow2` image is present\n- full serial output logging at debug level\n\n## Tested Versions\n\nTested with:\n\n- FortiGate 8.0.0 build 0167 GA debug image\n- FortiGate 7.6.6 build 3652 GA debug image\n- FortiGate 7.4.12 build 2902 GA\n- FortiGate 7.0.19 build 0696 GA\n- FortiGate 6.4.16 build 2098 GA\n- FortiProxy 7.6.6 build 1628 GA\n- FortiProxy 7.4.13 build 0722 GA debug image\n- FortiProxy 7.2.16 build 0465 GA\n- FortiProxy 7.0.23 build 0222 GA",
        "lineStart": 1,
        "lineEnd": 497,
        "totalLines": 497,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716563907,
      "end": 1793716563912
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/fortigate/docker/README.md"
}

Output

<path>/source/head/fortinet/fortigate/docker/README.md</path>
<type>file</type>
<content>
1: # Shared FortiOS Launcher Internals
2: 
3: The shared launcher source is in [`../../common`](../../common). The
4: FortiGate and FortiProxy Docker Makefiles stage that package with a small
5: product-specific `launch.py` wrapper. The public FortiGate API is documented in
6: [`../README.md`](../README.md). This file documents how the launcher works
7: inside the vrnetlab image and why some of the implementation looks unusual.
8: 
9: The launcher is built around serial-console automation. FortiOS does not expose
10: a stable early-boot API for the work this image needs to perform, so bootstrap
11: is modeled as three layers:
12: 
13: ```text
14: serial connection -> Terminal -> FOSCliDriver -> FOSCommander -> Features
15: ```
16: 
17: ## Three Layer Model
18: 
19: ### Terminal
20: 
21: `terminal.py` is the lowest layer. It wraps the vrnetlab telnet console and
22: provides buffered reads, regex matching, writes, and output suppression.
23: 
24: Important behavior:
25: 
26: - `Terminal.expect()` keeps unmatched bytes in an internal buffer across calls.
27:   FortiOS prompts and banners often arrive fragmented, so callers must not
28:   assume one read equals one logical event.
29: - A terminal-owned reader thread continuously drains the serial connection into
30:   a byte-counted, thread-safe queue. `Terminal.expect()` reads from that queue
31:   instead of making serial syscalls directly, so CLI state handling is not paced
32:   by each console read attempt. The FortiOS scrapli console exposes a blocking
33:   read for this thread; nonblocking eager reads remain only as a fallback for
34:   simpler connection wrappers.
35: - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of
36:   writing to the serial connection directly. The writer preserves write order
37:   and sends one queued chunk at a time, so commander/driver state handling is
38:   not paced by each scrapli write call.
39: - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte
40:   view of the matched prefix or, on timeout, the entire unmatched buffer.
41:   Inspecting timeout `Data` leaves those bytes buffered so later input can
42:   complete a partial token. Calling `discard()` explicitly consumes the view.
43:   `received_new_data` distinguishes fresh input from another inspection of the
44:   same retained bytes, so idle waits still advance the driver's stall timer.
45: - When multiple regexes match buffered output, the match that ends earliest
46:   wins. This avoids later, broader prompt patterns swallowing earlier prompts.
47: - Matched bytes are consumed from the buffer; bytes after the match stay queued
48:   for the next state parse.
49: - Timeout bytes are not consumed automatically. A command, feature, or commander
50:   inspection path must call `data.discard(...)` if it has assigned meaning to
51:   those bytes. Otherwise the bytes stay in the terminal buffer and can be
52:   matched again when later output completes a prompt or state.
53: - Retained terminal data is bounded by `FTNT_TERMINAL_BUFFER_LIMIT_BYTES`, which
54:   defaults to 1 MiB. If the buffer grows beyond that limit, bootstrap fails
55:   instead of truncating data, because oversized retained output means some layer
56:   failed to consume bytes it understood.
57: - The same limit bounds unread data in the reader queue and unsent data in the
58:   writer queue. When queued serial data reaches the limit, the reader or writer
59:   thread waits until the corresponding consumer drains queue bytes.
60: - `suppress_output()` temporarily prevents machine-readable commands such as
61:   `show` and `get system status` from being mirrored to the visible serial log,
62:   while still keeping their output available to the parser.
63: - `wait_write()` is legacy-compatible convenience glue. New bootstrap logic
64:   generally goes through `FOSCommander`, but `Terminal` still owns the raw IO
65:   primitives.
66: 
67: The terminal layer does not understand FortiOS. It only knows bytes, regexes,
68: and writes.
69: 
70: ### State Parsing
71: 
72: `fos_cli_driver.py` translates terminal output into `FOSCliState` events. It
73: owns login and interactive prompt handling:
74: 
75: - username prompt
76: - password prompt
77: - first-login password change
78: - current-password prompt after admin password changes
79: - credential rejection and blank-password fallback
80: - `Welcome!`
81: - command prompt
82: - reboot and shutdown messages
83: - license failure
84: - `--More--` pagination
85: - unknown output and timeout recovery
86: 
87: The driver runs in short spins. Each spin reads a state from `Terminal.expect()`,
88: handles login/pager responses itself, and then tells `FOSCommander` what state
89: was observed. Command dispatch is deliberately not done directly in the driver;
90: the driver only answers FortiOS protocol prompts and feeds state to the
91: dispatcher.
92: 
93: The driver does not decide whether unknown or prompt-echo output is meaningful.
94: It passes `Data` to the commander. If the downstream command, feature, or
95: commander inspection path discards it, the terminal buffer is updated through
96: the `Data` object. If it is not discarded, the bytes remain buffered.
97: 
98: There are two prompt-pattern phases:
99: 
100: - Before license and hostname changes, prompt matching accepts broad bootstrap
101:   hostnames because FortiOS can rename itself or switch to a licensed serial
102:   style.
103: - After hostname setup, the driver narrows login and command prompt patterns to
104:   the configured node hostname.
105: 
106: Unknown output is treated as a stall only after it keeps arriving without a
107: known state. The driver sends a small number of newlines to recover prompts,
108: then fails if FortiOS stays unparseable.
109: 
110: ### Command Dispatcher
111: 
112: `fos_commander.py` schedules feature commands. It is the only layer that knows
113: which bootstrap feature is active and which command is in flight.
114: 
115: Commands are represented by:
116: 
117: - `CommandSpec`: one FortiOS CLI line plus execution flags
118: - `ConfigBlock`: emits `config <scope>`, child commands, and `end`
119: - `EditBlock`: emits `edit <name>`, child commands, and `next`
120: - `CommandSequence`: emits child commands without config framing
121: 
122: Plain string commands are automatically wrapped in a default `CommandSpec`
123: when submitted directly or used inside any command container. Use an explicit
124: `CommandSpec` only when a command needs non-default execution flags.
125: 
126: `CommandSpec` intentionally has no separate name field. The command line is the
127: identity, and feature state machines track phase when they need context.
128: 
129: The dispatcher sends one command at a time and waits for an appropriate state
130: before continuing. By default, a command completes at the next command prompt.
131: Some commands override completion states, for example confirmation prompts or
132: reboot messages.
133: 
134: Scope-closing commands (`next` and `end`) always capture their output and check
135: for `Command fail. Return code <number>`, including builds that append a period
136: after the code. A closing failure stops the feature before completion callbacks
137: or further commands, even when `fail_on_error=False`. It follows the bootstrap
138: error policy: abort normally, or skip the failed feature when
139: `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for
140: individual `set` commands, which can deliberately tolerate unsupported fields.
141: 
142: Session loss is explicit. Each command carries a `SessionLossAction`:
143: 
144: - `RESTART_BLOCK`: replay the current block from the start
145: - `COMPLETE_BLOCK`: treat the block as complete
146: - `CONTINUE`: do not replay the disruptive command
147: - `VALIDATE`: reserve for commands that need post-loss validation
148: - `FAIL`: report failure through the configured bootstrap error policy
149: 
150: This matters because commands such as license restore and password updates can
151: drop the active admin session. Replaying them blindly can corrupt state or loop.
152: 
153: Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.
154: The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,
155: commands that allow session-loss replay also allow context-loss replay; commands
156: with another session-loss policy decline context-loss replay unless explicitly
157: configured otherwise. Context loss does not invoke session-loss callbacks, since
158: those may commit credential or licensing transitions.
159: 
160: The commander allows one recovery per command position within a submitted block,
161: shared between context loss and session loss. Recovery replays the block's scope
162: openers and commands. If necessary, the commander sends one `abort` to restore
163: the block's initial prompt context before replay. A repeated loss at the same
164: command or failure to restore that context follows the bootstrap error policy.
165: The allowance resets when the feature submits a new block. Cleanup commands also
166: have one session-loss retry. Attempts expose `retry_count` and the prompt context
167: before and after execution so features can make their recovery decision.
168: 
169: The dispatcher also manages cleanup actions and standard-output contexts.
170: Features can request console output mode `standard` for machine-readable output;
171: the dispatcher detects the current console mode, changes it only when needed,
172: and restores `more` after the feature completes.
173: 
174: ## Output Handling
175: 
176: All CLI output passed into `FOSCommander` is `terminal.Data`. The commander does
177: not accept raw bytes and does not own output buffering. The output path is:
178: 
179: ```text
180: Terminal.expect() -> Data -> FOSCliDriver -> FOSCommander
181: ```
182: 
183: When output arrives while a command is in flight, the commander offers it in
184: this order:
185: 
186: ```text
187: CommandAttempt.on_output(data)
188: Feature.on_output(data)
189: FOSCommander._inspect_output(data)
190: ```
191: 
192: The first layer that understands the data consumes it by calling
193: `data.discard(...)`. Consumption has two effects:
194: 
195: - the consumer records whatever state it needs, such as command output
196: - the terminal buffer discards the consumed bytes when the `Data` object is a
197:   timeout view into retained terminal data
198: 
199: Command output capture belongs to `CommandAttempt`. If a command has
200: `capture_output=True`, `CommandAttempt.on_output(data)` appends
201: `bytes(data)` to `command.output` and discards those bytes. When the command
202: finishes, the feature receives the completed command:
203: 
204: ```text
205: on_command_executed(command, state)
206: ```
207: 
208: Features inspect `command.spec` to know which command completed and
209: `bytes(command.output)` to inspect captured output. Features should not
210: reconstruct command output from commander state.
211: 
212: `Feature.on_output(data)` remains for out-of-band streams. For example, a
213: feature may start a debug command and wait for asynchronous data that is not the
214: normal command completion transcript. If the feature recognizes that data, it
215: must call `data.discard(...)` before returning true. If it does not recognize
216: the data, it returns false and the commander can inspect it or leave it buffered.
217: 
218: Prompt echo uses the same path. `CMD_PROMPT_ECHO` is not special-cased with a
219: separate parser in the commander. The driver passes the prompt-echo `Data` to
220: `FOSCommander.on_prompt_echo()`, which calls `on_output(data)`. If any layer
221: discards the data, no recovery newline is sent. If no layer consumes it, the
222: commander sends a newline to request a clean prompt.
223: 
224: This is the critical invariant: output that has been assigned meaning must be
225: discarded through `Data`; output that is not understood must remain buffered so
226: it can be completed by later serial data.
227: 
228: The retained terminal buffer has a hard upper bound. The default is 1 MiB, set
229: with `FTNT_TERMINAL_BUFFER_LIMIT_BYTES` when a larger diagnostic window is needed.
230: The limit is intentionally enforced as an error rather than a ring buffer: if
231: retained data grows without being consumed, the command/feature/commander stack
232: has lost ownership of some output and continuing would risk replaying stale
233: bytes into later state decisions.
234: 
235: ## Feature Architecture
236: 
237: Bootstrap work is split into feature objects under `common/features/`. A feature has a
238: name, lifecycle hooks, optional file-watch integration, and zero or more command
239: blocks.
240: 
241: The core lifecycle is:
242: 
243: ```text
244: begin_activation()
245:  promactivate()
246: on_command_dispatched(attempt)
247: on_output(output)
248: on_command_executed(command, state)
249: on_block_complete()
250: on_session_loss(attempt)
251: on_context_loss(attempt)
252: mark_completed()
253: ```
254: 
255: Static command features subclass `StaticFeature`; they submit a fixed list of
256: blocks and complete after the last block. Dynamic features subclass `Feature`
257: and submit follow-up blocks based on command output or timer ticks.
258: 
259: Current bootstrap stages are:
260: 
261: - `disk-format`: formats additional disks after the first FortiGate log disk
262: - `admin`: disables password policy, creates/updates the desired admin, then
263:   logs out and waits for console authentication before later stages run
264: - `image-info`: reads `get system status` once and stores the parsed
265:   platform, major, minor, patch, and build on `vm.fos_version` for later
266:   features
267: - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against
268:   the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint
269: - `management`: configures `port1`, FortiGuard interface selection, and the
270:   management route for static management addressing
271: - `bootstrap-dns`: temporarily sets DNS for license/bootstrap reachability
272: - `fortiguard-hooks`: applies the optional `DIAG_2`/`DIAG_1` guard commands and
273:   the FortiGuard settings used when the hooks are enabled
274: - `setup-license`: restores `/tftpboot/appliance.lic` over TFTP and handles reboot
275: - `default-config`: applies launcher-owned defaults such as `admin-scp` and the
276:   final hostname
277: - `management-after-license`: reapplies management after license restore because
278:   FortiOS can remove routes or drop sessions when registration state changes
279: - `fortiguard-hooks-after-license`: reapplies the FortiGuard hook settings after
280:   the license reboot whenever `FTNT_FORTIGUARD_HOOKS` is enabled
281: - `license-validation`: accepts `Valid`, and accepts `Grace Period` unless
282:   `FTNT_WAIT_FOR_VALID_LICENSE=true`; `Pending` and strict-mode `Grace Period`
283:   are retried until the configured timeout
284: - `management-vrf`: moves management into VRF 1 when supported, or narrows
285:   the management route on FortiProxy
286: - `undo-bootstrap-dns`: removes the temporary bootstrap DNS settings
287: - `fortitoken-provisioning`: after a license becomes `VALID`, polls for
288:   license-provisioned FortiTokens for up to 15 seconds
289: - `capture-config`: records a clean baseline and later services `/get-config`
290:   runtime captures
291: - `pki-certificates`: installs CA, local, remote, and CRL objects from
292:   `FTNT_PKI_*` path variables; failed config installs fall back to TFTP where
293:   supported, warning on successful fallback and failing bootstrap if both
294:   methods fail
295: - `startup-config`: imports the user-supplied startup config
296: 
297: `FeatureFileWatcher` polls watched feature paths after bootstrap. Today the
298: main runtime feature is config capture: writing a request to `/get-config`
299: enqueues the capture feature after the launcher reconnects to the serial
300: console. A trigger created *or modified* between polls is a new request
301: (`on_file_detected` and `on_file_modified` share one handler), so a client
302: that re-writes the trigger while an earlier capture is still running is not
303: silently dropped. Each request is answered by one JSON status record per
304: request id under `/config/get-config.status.d/<id>.json`
305: (`{"id", "status": pending|success|busy|error, "output"?, "error"?}`),
306: written atomically; records older than 120 s are swept when a new request
307: is accepted. An empty trigger (a human `touch`) still works and gets a
308: generated id. See the `fortigate/README.md` "Saving Config" section.
309: 
310: Bootstrap feature errors are fatal by default. With
311: `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, a failed feature is logged and skipped
312: when FortiOS is back at a command prompt, and the remaining startup features
313: continue. This is best effort: commands that already ran are not undone, and a
314: run with skipped features is not reported healthy. Credential fallback remains
315: unresolved until the desired credentials authenticate successfully; unresolved
316: fallback also keeps the VM unhealthy. After a desired-password rejection, the
317: launcher retries the last accepted credentials once for that login regardless
318: of the bootstrap error policy, while retaining the desired
319: credentials for later logins. It does not replay an admin password-change block
320: after FortiOS has committed it. If the CLI is at an interactive prompt or both
321: credential attempts fail, bootstrap halts, keeps the VM running, and releases
322: the launcher's serial Telnet connection for manual repair. Runtime feature
323: failures, such as a `/get-config` request, remain request errors and do not
324: change this bootstrap policy.
325: 
326: The feature architecture is intentionally serial. FortiOS CLI state is global,
327: the console has one prompt stream, and several operations can reboot or remove
328: admin sessions. Parallel feature execution would make recovery ambiguous.
329: 
330: ## Design Quirks
331: 
332: ### Password handling is deliberately conservative
333: 
334: FortiOS versions differ in default credential behavior. Some accept the default
335: password, some require first-login password changes, and some older paths accept
336: a blank default password first. The driver keeps separate bootstrap and desired
337: credentials so it can answer prompts with the password that is valid at that
338: moment.
339: 
340: The desired credentials are activated after the admin edit commits. Password
341: command output is checked for FortiOS command failures. After closing the admin
342: configuration, the feature sends `exit` and waits for a successful login and CLI
343: prompt before completing. A logout during the commit also activates the new
344: credentials without replaying the password change. The driver first tries the
345: desired credentials. If FortiOS rejects
346: them, it retries immediately with the previously accepted credentials, without
347: replacing the desired credentials used for later logins.
348: 
349: ### Prompt patterns change during bootstrap
350: 
351: License installation and hostname changes can alter prompt text. During license
352: restore the driver broadens prompt matching; after `set hostname`, it narrows
353: patterns to the configured hostname. This is why prompt handling lives in the
354: driver rather than directly in features.
355: 
356: ### Console pagination is not globally disabled forever
357: 
358: Machine-readable commands need unpaginated output, but interactive users expect
359: FortiOS's normal paginated console. The commander temporarily switches to
360: `standard` output for captures and polls, then restores `more` if it changed
361: the setting.
362: 
363: ### Config capture is delta-based
364: 
365: The launcher captures a baseline before user startup config. Later `/get-config`
366: captures run `show`, clean terminal artifacts, parse config/edit blocks, and
367: write only changes to `/config/current.conf`.
368: 
369: Encrypted fields are noisy because FortiOS can emit different `ENC` values for
370: the same effective secret. The diff code can ignore ENC-only changes for
371: existing entries when configured, but it still retains encrypted fields for new
372: entries or entries with other body changes.
373: 
374: ### Feature names are workflow controls, not command labels
375: 
376: Feature names are used for logging, debug cutoffs, and undo stages. Individual
377: commands are identified by their CLI line. When a workflow needs to distinguish
378: steps, it tracks its own phase instead of attaching synthetic names to commands.
379: 
380: ## Gotchas And Required Hoop-Jumps
381: 
382: - Bootstrap must run through the serial console. SSH is not reliable until
383:   credentials, management, license state, and prompt patterns settle.
384: - License restore can reboot FortiOS and can remove the active admin session.
385:   The `setup-license` feature marks those commands as non-replayable and waits
386:   for the next prompt instead.
387: - Management configuration is applied more than once. License registration can
388:   disturb routes and sessions, so `management-after-license` repairs management
389:   before license polling.
390: - FortiProxy does not support interface VRFs in the same way FortiGate does.
391:   `management-vrf` detects `set vrf 1` failures and falls back to a
392:   management-gateway route destination instead of installing a broad default
393:   route.
394: - TFTP needs special handling in both management modes. The license file is
395:   restored from `/tftpboot/appliance.lic`; the VM must be able to reach the
396:   launcher TFTP service from its management interface during bootstrap.
397: - The QEMU management MAC can come from snapshot metadata or vrnetlab's generated
398:   MAC. In passthrough mode the container `eth0` MAC is changed to the VM
399:   management MAC so redirected management traffic looks consistent.
400: - The launcher writes files inside `/config` and the node config mount. These
401:   files are part of runtime behavior, not source artifacts.
402: - The Makefile copies only regular files from `../../common` into this directory
403:   during image build. Python cache directories under `common/` must not enter
404:   the Docker build context as copied launcher assets.
405: 
406: ## Management Networking
407: 
408: The management strategy is selected before the VM is created. Both strategies
409: implement `NetMgmtStrategy`, which supplies QEMU `-netdev` arguments and writes
410: strategy-specific host/container networking.
411: 
412: ### Host-Forwarded Mode
413: 
414: `HostForwardedBridge` is used when management passthrough is disabled. It
415: creates an internal bridge named `br-mgmt` and gives the FortiGate a point to
416: point management network:
417: 
418: ```text
419: container bridge: 172.31.255.29/30, 200::/127
420: FortiGate port1: 172.31.255.30/30, 200::1/127
421: ```
422: 
423: QEMU attaches `port1` with:
424: 
425: ```text
426: -netdev bridge,br=br-mgmt,id=p00
427: ```
428: 
429: The container installs NAT rules:
430: 
431: - inbound TCP on `eth0`, except serial port `5000`, is DNATed to the FortiGate
432:   management address
433: - inbound UDP on `eth0` is DNATed to the FortiGate management address
434: - traffic leaving `br-mgmt` is masqueraded so FortiOS replies through the bridge
435: - traffic from FortiOS out through `eth0` is masqueraded for breakout
436: 
437: IPv6 forwarding is enabled in the container and equivalent IPv6 NAT rules are
438: installed. The bridge is allowed through QEMU bridge configuration with
439: `/etc/qemu/bridge.conf`.
440: 
441: In this mode the TFTP server runs in the container's normal namespace. UDP DNAT
442: lets FortiOS reach it through the host-forwarded management path.
443: 
444: This mode keeps Containerlab's management network connected to the container,
445: not directly to FortiOS. It is easier to reason about as NAT/port-forwarding,
446: but it means all management services except serial are forwarded through the
447: container.
448: 
449: ### Passthrough Mode
450: 
451: `PassthroughRedirect` is the default mode. It makes FortiGate `port1` appear to
452: participate directly in the Containerlab management network.
453: 
454: QEMU attaches `port1` with a tap:
455: 
456: ```text
457: -netdev tap,ifname=tap0,id=p00,script=/etc/tc-tap-mgmt-ifup,downscript=no
458: ```
459: 
460: The generated ifup script:
461: 
462: - brings up `tap0`
463: - disables IPv6 addresses on `tap0` to avoid container-originated IPv6 chatter
464: - adds `clsact` qdiscs to `eth0`, `tap0`, and the redirect veth
465: - passes TCP ports `5000-5007` so serial consoles stay on the container
466: - mirrors ARP from `eth0` to `tap0`
467: - redirects most ingress `eth0` traffic to `tap0`
468: - redirects ingress `tap0` traffic back to `eth0`
469: - changes container `eth0` to the VM management MAC
470: 
471: Passthrough mode also creates a private namespace named `fakehost` with a veth
472: pair:
473: 
474: ```text
475: root namespace: RA
476: fakehost namespace: FA
477: ```
478: 
479: The namespace exists so launcher-owned services, currently TFTP, can still live
480: "beside" the VM even though normal management traffic is redirected straight
481: between the Containerlab management network and the VM tap.
482: 
483: The namespace starts with a temporary address so services can bind before QEMU
484: calls the tap ifup script. During ifup, the temporary address is replaced with
485: the management gateway address that FortiOS expects. `tc flower` rules redirect
486: selected service ports from the VM to the namespace and rewrite Ethernet
487: destinations so the veth path works:
488: 
489: - VM -> namespace traffic is matched on protocol, destination port, and gateway
490:   IP, then redirected from `tap0` to `RA`
491: - namespace -> VM return traffic is matched on source port and FortiGate
492:   management IP, then redirected back to `tap0` with the VM MAC
493: 
494: The TFTP server runs inside `fakehost` in passthrough mode, with a fixed TID
495: port range so the flower rules can match both the initial TFTP request and
496: server-selected data ports.
497: 
498: Passthrough gives the most natural Containerlab management behavior, but it is
499: the most fragile path: MAC rewriting, tap setup timing, namespace addressing,
500: and tc filter order all need to line up before license restore can work.

(End of file - total 500 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d6b004001gOcZSw4RTMRdDD",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6a6f5001olbbGFgBgts46C",
  "callID": "call_2842e1143a5044478224ff5f",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/fortigate/docker/README.md"
    },
    "output": "<path>/source/head/fortinet/fortigate/docker/README.md</path>\n<type>file</type>\n<content>\n1: # Shared FortiOS Launcher Internals\n2: \n3: The shared launcher source is in [`../../common`](../../common). The\n4: FortiGate and FortiProxy Docker Makefiles stage that package with a small\n5: product-specific `launch.py` wrapper. The public FortiGate API is documented in\n6: [`../README.md`](../README.md). This file documents how the launcher works\n7: inside the vrnetlab image and why some of the implementation looks unusual.\n8: \n9: The launcher is built around serial-console automation. FortiOS does not expose\n10: a stable early-boot API for the work this image needs to perform, so bootstrap\n11: is modeled as three layers:\n12: \n13: ```text\n14: serial connection -> Terminal -> FOSCliDriver -> FOSCommander -> Features\n15: ```\n16: \n17: ## Three Layer Model\n18: \n19: ### Terminal\n20: \n21: `terminal.py` is the lowest layer. It wraps the vrnetlab telnet console and\n22: provides buffered reads, regex matching, writes, and output suppression.\n23: \n24: Important behavior:\n25: \n26: - `Terminal.expect()` keeps unmatched bytes in an internal buffer across calls.\n27:   FortiOS prompts and banners often arrive fragmented, so callers must not\n28:   assume one read equals one logical event.\n29: - A terminal-owned reader thread continuously drains the serial connection into\n30:   a byte-counted, thread-safe queue. `Terminal.expect()` reads from that queue\n31:   instead of making serial syscalls directly, so CLI state handling is not paced\n32:   by each console read attempt. The FortiOS scrapli console exposes a blocking\n33:   read for this thread; nonblocking eager reads remain only as a fallback for\n34:   simpler connection wrappers.\n35: - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n36:   writing to the serial connection directly. The writer preserves write order\n37:   and sends one queued chunk at a time, so commander/driver state handling is\n38:   not paced by each scrapli write call.\n39: - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n40:   view of the matched prefix or, on timeout, the entire unmatched buffer.\n41:   Inspecting timeout `Data` leaves those bytes buffered so later input can\n42:   complete a partial token. Calling `discard()` explicitly consumes the view.\n43:   `received_new_data` distinguishes fresh input from another inspection of the\n44:   same retained bytes, so idle waits still advance the driver's stall timer.\n45: - When multiple regexes match buffered output, the match that ends earliest\n46:   wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n47: - Matched bytes are consumed from the buffer; bytes after the match stay queued\n48:   for the next state parse.\n49: - Timeout bytes are not consumed automatically. A command, feature, or commander\n50:   inspection path must call `data.discard(...)` if it has assigned meaning to\n51:   those bytes. Otherwise the bytes stay in the terminal buffer and can be\n52:   matched again when later output completes a prompt or state.\n53: - Retained terminal data is bounded by `FTNT_TERMINAL_BUFFER_LIMIT_BYTES`, which\n54:   defaults to 1 MiB. If the buffer grows beyond that limit, bootstrap fails\n55:   instead of truncating data, because oversized retained output means some layer\n56:   failed to consume bytes it understood.\n57: - The same limit bounds unread data in the reader queue and unsent data in the\n58:   writer queue. When queued serial data reaches the limit, the reader or writer\n59:   thread waits until the corresponding consumer drains queue bytes.\n60: - `suppress_output()` temporarily prevents machine-readable commands such as\n61:   `show` and `get system status` from being mirrored to the visible serial log,\n62:   while still keeping their output available to the parser.\n63: - `wait_write()` is legacy-compatible convenience glue. New bootstrap logic\n64:   generally goes through `FOSCommander`, but `Terminal` still owns the raw IO\n65:   primitives.\n66: \n67: The terminal layer does not understand FortiOS. It only knows bytes, regexes,\n68: and writes.\n69: \n70: ### State Parsing\n71: \n72: `fos_cli_driver.py` translates terminal output into `FOSCliState` events. It\n73: owns login and interactive prompt handling:\n74: \n75: - username prompt\n76: - password prompt\n77: - first-login password change\n78: - current-password prompt after admin password changes\n79: - credential rejection and blank-password fallback\n80: - `Welcome!`\n81: - command prompt\n82: - reboot and shutdown messages\n83: - license failure\n84: - `--More--` pagination\n85: - unknown output and timeout recovery\n86: \n87: The driver runs in short spins. Each spin reads a state from `Terminal.expect()`,\n88: handles login/pager responses itself, and then tells `FOSCommander` what state\n89: was observed. Command dispatch is deliberately not done directly in the driver;\n90: the driver only answers FortiOS protocol prompts and feeds state to the\n91: dispatcher.\n92: \n93: The driver does not decide whether unknown or prompt-echo output is meaningful.\n94: It passes `Data` to the commander. If the downstream command, feature, or\n95: commander inspection path discards it, the terminal buffer is updated through\n96: the `Data` object. If it is not discarded, the bytes remain buffered.\n97: \n98: There are two prompt-pattern phases:\n99: \n100: - Before license and hostname changes, prompt matching accepts broad bootstrap\n101:   hostnames because FortiOS can rename itself or switch to a licensed serial\n102:   style.\n103: - After hostname setup, the driver narrows login and command prompt patterns to\n104:   the configured node hostname.\n105: \n106: Unknown output is treated as a stall only after it keeps arriving without a\n107: known state. The driver sends a small number of newlines to recover prompts,\n108: then fails if FortiOS stays unparseable.\n109: \n110: ### Command Dispatcher\n111: \n112: `fos_commander.py` schedules feature commands. It is the only layer that knows\n113: which bootstrap feature is active and which command is in flight.\n114: \n115: Commands are represented by:\n116: \n117: - `CommandSpec`: one FortiOS CLI line plus execution flags\n118: - `ConfigBlock`: emits `config <scope>`, child commands, and `end`\n119: - `EditBlock`: emits `edit <name>`, child commands, and `next`\n120: - `CommandSequence`: emits child commands without config framing\n121: \n122: Plain string commands are automatically wrapped in a default `CommandSpec`\n123: when submitted directly or used inside any command container. Use an explicit\n124: `CommandSpec` only when a command needs non-default execution flags.\n125: \n126: `CommandSpec` intentionally has no separate name field. The command line is the\n127: identity, and feature state machines track phase when they need context.\n128: \n129: The dispatcher sends one command at a time and waits for an appropriate state\n130: before continuing. By default, a command completes at the next command prompt.\n131: Some commands override completion states, for example confirmation prompts or\n132: reboot messages.\n133: \n134: Scope-closing commands (`next` and `end`) always capture their output and check\n135: for `Command fail. Return code <number>`, including builds that append a period\n136: after the code. A closing failure stops the feature before completion callbacks\n137: or further commands, even when `fail_on_error=False`. It follows the bootstrap\n138: error policy: abort normally, or skip the failed feature when\n139: `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n140: individual `set` commands, which can deliberately tolerate unsupported fields.\n141: \n142: Session loss is explicit. Each command carries a `SessionLossAction`:\n143: \n144: - `RESTART_BLOCK`: replay the current block from the start\n145: - `COMPLETE_BLOCK`: treat the block as complete\n146: - `CONTINUE`: do not replay the disruptive command\n147: - `VALIDATE`: reserve for commands that need post-loss validation\n148: - `FAIL`: report failure through the configured bootstrap error policy\n149: \n150: This matters because commands such as license restore and password updates can\n151: drop the active admin session. Replaying them blindly can corrupt state or loop.\n152: \n153: Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n154: The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n155: commands that allow session-loss replay also allow context-loss replay; commands\n156: with another session-loss policy decline context-loss replay unless explicitly\n157: configured otherwise. Context loss does not invoke session-loss callbacks, since\n158: those may commit credential or licensing transitions.\n159: \n160: The commander allows one recovery per command position within a submitted block,\n161: shared between context loss and session loss. Recovery replays the block's scope\n162: openers and commands. If necessary, the commander sends one `abort` to restore\n163: the block's initial prompt context before replay. A repeated loss at the same\n164: command or failure to restore that context follows the bootstrap error policy.\n165: The allowance resets when the feature submits a new block. Cleanup commands also\n166: have one session-loss retry. Attempts expose `retry_count` and the prompt context\n167: before and after execution so features can make their recovery decision.\n168: \n169: The dispatcher also manages cleanup actions and standard-output contexts.\n170: Features can request console output mode `standard` for machine-readable output;\n171: the dispatcher detects the current console mode, changes it only when needed,\n172: and restores `more` after the feature completes.\n173: \n174: ## Output Handling\n175: \n176: All CLI output passed into `FOSCommander` is `terminal.Data`. The commander does\n177: not accept raw bytes and does not own output buffering. The output path is:\n178: \n179: ```text\n180: Terminal.expect() -> Data -> FOSCliDriver -> FOSCommander\n181: ```\n182: \n183: When output arrives while a command is in flight, the commander offers it in\n184: this order:\n185: \n186: ```text\n187: CommandAttempt.on_output(data)\n188: Feature.on_output(data)\n189: FOSCommander._inspect_output(data)\n190: ```\n191: \n192: The first layer that understands the data consumes it by calling\n193: `data.discard(...)`. Consumption has two effects:\n194: \n195: - the consumer records whatever state it needs, such as command output\n196: - the terminal buffer discards the consumed bytes when the `Data` object is a\n197:   timeout view into retained terminal data\n198: \n199: Command output capture belongs to `CommandAttempt`. If a command has\n200: `capture_output=True`, `CommandAttempt.on_output(data)` appends\n201: `bytes(data)` to `command.output` and discards those bytes. When the command\n202: finishes, the feature receives the completed command:\n203: \n204: ```text\n205: on_command_executed(command, state)\n206: ```\n207: \n208: Features inspect `command.spec` to know which command completed and\n209: `bytes(command.output)` to inspect captured output. Features should not\n210: reconstruct command output from commander state.\n211: \n212: `Feature.on_output(data)` remains for out-of-band streams. For example, a\n213: feature may start a debug command and wait for asynchronous data that is not the\n214: normal command completion transcript. If the feature recognizes that data, it\n215: must call `data.discard(...)` before returning true. If it does not recognize\n216: the data, it returns false and the commander can inspect it or leave it buffered.\n217: \n218: Prompt echo uses the same path. `CMD_PROMPT_ECHO` is not special-cased with a\n219: separate parser in the commander. The driver passes the prompt-echo `Data` to\n220: `FOSCommander.on_prompt_echo()`, which calls `on_output(data)`. If any layer\n221: discards the data, no recovery newline is sent. If no layer consumes it, the\n222: commander sends a newline to request a clean prompt.\n223: \n224: This is the critical invariant: output that has been assigned meaning must be\n225: discarded through `Data`; output that is not understood must remain buffered so\n226: it can be completed by later serial data.\n227: \n228: The retained terminal buffer has a hard upper bound. The default is 1 MiB, set\n229: with `FTNT_TERMINAL_BUFFER_LIMIT_BYTES` when a larger diagnostic window is needed.\n230: The limit is intentionally enforced as an error rather than a ring buffer: if\n231: retained data grows without being consumed, the command/feature/commander stack\n232: has lost ownership of some output and continuing would risk replaying stale\n233: bytes into later state decisions.\n234: \n235: ## Feature Architecture\n236: \n237: Bootstrap work is split into feature objects under `common/features/`. A feature has a\n238: name, lifecycle hooks, optional file-watch integration, and zero or more command\n239: blocks.\n240: \n241: The core lifecycle is:\n242: \n243: ```text\n244: begin_activation()\n245:  promactivate()\n246: on_command_dispatched(attempt)\n247: on_output(output)\n248: on_command_executed(command, state)\n249: on_block_complete()\n250: on_session_loss(attempt)\n251: on_context_loss(attempt)\n252: mark_completed()\n253: ```\n254: \n255: Static command features subclass `StaticFeature`; they submit a fixed list of\n256: blocks and complete after the last block. Dynamic features subclass `Feature`\n257: and submit follow-up blocks based on command output or timer ticks.\n258: \n259: Current bootstrap stages are:\n260: \n261: - `disk-format`: formats additional disks after the first FortiGate log disk\n262: - `admin`: disables password policy, creates/updates the desired admin, then\n263:   logs out and waits for console authentication before later stages run\n264: - `image-info`: reads `get system status` once and stores the parsed\n265:   platform, major, minor, patch, and build on `vm.fos_version` for later\n266:   features\n267: - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n268:   the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n269: - `management`: configures `port1`, FortiGuard interface selection, and the\n270:   management route for static management addressing\n271: - `bootstrap-dns`: temporarily sets DNS for license/bootstrap reachability\n272: - `fortiguard-hooks`: applies the optional `DIAG_2`/`DIAG_1` guard commands and\n273:   the FortiGuard settings used when the hooks are enabled\n274: - `setup-license`: restores `/tftpboot/appliance.lic` over TFTP and handles reboot\n275: - `default-config`: applies launcher-owned defaults such as `admin-scp` and the\n276:   final hostname\n277: - `management-after-license`: reapplies management after license restore because\n278:   FortiOS can remove routes or drop sessions when registration state changes\n279: - `fortiguard-hooks-after-license`: reapplies the FortiGuard hook settings after\n280:   the license reboot whenever `FTNT_FORTIGUARD_HOOKS` is enabled\n281: - `license-validation`: accepts `Valid`, and accepts `Grace Period` unless\n282:   `FTNT_WAIT_FOR_VALID_LICENSE=true`; `Pending` and strict-mode `Grace Period`\n283:   are retried until the configured timeout\n284: - `management-vrf`: moves management into VRF 1 when supported, or narrows\n285:   the management route on FortiProxy\n286: - `undo-bootstrap-dns`: removes the temporary bootstrap DNS settings\n287: - `fortitoken-provisioning`: after a license becomes `VALID`, polls for\n288:   license-provisioned FortiTokens for up to 15 seconds\n289: - `capture-config`: records a clean baseline and later services `/get-config`\n290:   runtime captures\n291: - `pki-certificates`: installs CA, local, remote, and CRL objects from\n292:   `FTNT_PKI_*` path variables; failed config installs fall back to TFTP where\n293:   supported, warning on successful fallback and failing bootstrap if both\n294:   methods fail\n295: - `startup-config`: imports the user-supplied startup config\n296: \n297: `FeatureFileWatcher` polls watched feature paths after bootstrap. Today the\n298: main runtime feature is config capture: writing a request to `/get-config`\n299: enqueues the capture feature after the launcher reconnects to the serial\n300: console. A trigger created *or modified* between polls is a new request\n301: (`on_file_detected` and `on_file_modified` share one handler), so a client\n302: that re-writes the trigger while an earlier capture is still running is not\n303: silently dropped. Each request is answered by one JSON status record per\n304: request id under `/config/get-config.status.d/<id>.json`\n305: (`{\"id\", \"status\": pending|success|busy|error, \"output\"?, \"error\"?}`),\n306: written atomically; records older than 120 s are swept when a new request\n307: is accepted. An empty trigger (a human `touch`) still works and gets a\n308: generated id. See the `fortigate/README.md` \"Saving Config\" section.\n309: \n310: Bootstrap feature errors are fatal by default. With\n311: `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, a failed feature is logged and skipped\n312: when FortiOS is back at a command prompt, and the remaining startup features\n313: continue. This is best effort: commands that already ran are not undone, and a\n314: run with skipped features is not reported healthy. Credential fallback remains\n315: unresolved until the desired credentials authenticate successfully; unresolved\n316: fallback also keeps the VM unhealthy. After a desired-password rejection, the\n317: launcher retries the last accepted credentials once for that login regardless\n318: of the bootstrap error policy, while retaining the desired\n319: credentials for later logins. It does not replay an admin password-change block\n320: after FortiOS has committed it. If the CLI is at an interactive prompt or both\n321: credential attempts fail, bootstrap halts, keeps the VM running, and releases\n322: the launcher's serial Telnet connection for manual repair. Runtime feature\n323: failures, such as a `/get-config` request, remain request errors and do not\n324: change this bootstrap policy.\n325: \n326: The feature architecture is intentionally serial. FortiOS CLI state is global,\n327: the console has one prompt stream, and several operations can reboot or remove\n328: admin sessions. Parallel feature execution would make recovery ambiguous.\n329: \n330: ## Design Quirks\n331: \n332: ### Password handling is deliberately conservative\n333: \n334: FortiOS versions differ in default credential behavior. Some accept the default\n335: password, some require first-login password changes, and some older paths accept\n336: a blank default password first. The driver keeps separate bootstrap and desired\n337: credentials so it can answer prompts with the password that is valid at that\n338: moment.\n339: \n340: The desired credentials are activated after the admin edit commits. Password\n341: command output is checked for FortiOS command failures. After closing the admin\n342: configuration, the feature sends `exit` and waits for a successful login and CLI\n343: prompt before completing. A logout during the commit also activates the new\n344: credentials without replaying the password change. The driver first tries the\n345: desired credentials. If FortiOS rejects\n346: them, it retries immediately with the previously accepted credentials, without\n347: replacing the desired credentials used for later logins.\n348: \n349: ### Prompt patterns change during bootstrap\n350: \n351: License installation and hostname changes can alter prompt text. During license\n352: restore the driver broadens prompt matching; after `set hostname`, it narrows\n353: patterns to the configured hostname. This is why prompt handling lives in the\n354: driver rather than directly in features.\n355: \n356: ### Console pagination is not globally disabled forever\n357: \n358: Machine-readable commands need unpaginated output, but interactive users expect\n359: FortiOS's normal paginated console. The commander temporarily switches to\n360: `standard` output for captures and polls, then restores `more` if it changed\n361: the setting.\n362: \n363: ### Config capture is delta-based\n364: \n365: The launcher captures a baseline before user startup config. Later `/get-config`\n366: captures run `show`, clean terminal artifacts, parse config/edit blocks, and\n367: write only changes to `/config/current.conf`.\n368: \n369: Encrypted fields are noisy because FortiOS can emit different `ENC` values for\n370: the same effective secret. The diff code can ignore ENC-only changes for\n371: existing entries when configured, but it still retains encrypted fields for new\n372: entries or entries with other body changes.\n373: \n374: ### Feature names are workflow controls, not command labels\n375: \n376: Feature names are used for logging, debug cutoffs, and undo stages. Individual\n377: commands are identified by their CLI line. When a workflow needs to distinguish\n378: steps, it tracks its own phase instead of attaching synthetic names to commands.\n379: \n380: ## Gotchas And Required Hoop-Jumps\n381: \n382: - Bootstrap must run through the serial console. SSH is not reliable until\n383:   credentials, management, license state, and prompt patterns settle.\n384: - License restore can reboot FortiOS and can remove the active admin session.\n385:   The `setup-license` feature marks those commands as non-replayable and waits\n386:   for the next prompt instead.\n387: - Management configuration is applied more than once. License registration can\n388:   disturb routes and sessions, so `management-after-license` repairs management\n389:   before license polling.\n390: - FortiProxy does not support interface VRFs in the same way FortiGate does.\n391:   `management-vrf` detects `set vrf 1` failures and falls back to a\n392:   management-gateway route destination instead of installing a broad default\n393:   route.\n394: - TFTP needs special handling in both management modes. The license file is\n395:   restored from `/tftpboot/appliance.lic`; the VM must be able to reach the\n396:   launcher TFTP service from its management interface during bootstrap.\n397: - The QEMU management MAC can come from snapshot metadata or vrnetlab's generated\n398:   MAC. In passthrough mode the container `eth0` MAC is changed to the VM\n399:   management MAC so redirected management traffic looks consistent.\n400: - The launcher writes files inside `/config` and the node config mount. These\n401:   files are part of runtime behavior, not source artifacts.\n402: - The Makefile copies only regular files from `../../common` into this directory\n403:   during image build. Python cache directories under `common/` must not enter\n404:   the Docker build context as copied launcher assets.\n405: \n406: ## Management Networking\n407: \n408: The management strategy is selected before the VM is created. Both strategies\n409: implement `NetMgmtStrategy`, which supplies QEMU `-netdev` arguments and writes\n410: strategy-specific host/container networking.\n411: \n412: ### Host-Forwarded Mode\n413: \n414: `HostForwardedBridge` is used when management passthrough is disabled. It\n415: creates an internal bridge named `br-mgmt` and gives the FortiGate a point to\n416: point management network:\n417: \n418: ```text\n419: container bridge: 172.31.255.29/30, 200::/127\n420: FortiGate port1: 172.31.255.30/30, 200::1/127\n421: ```\n422: \n423: QEMU attaches `port1` with:\n424: \n425: ```text\n426: -netdev bridge,br=br-mgmt,id=p00\n427: ```\n428: \n429: The container installs NAT rules:\n430: \n431: - inbound TCP on `eth0`, except serial port `5000`, is DNATed to the FortiGate\n432:   management address\n433: - inbound UDP on `eth0` is DNATed to the FortiGate management address\n434: - traffic leaving `br-mgmt` is masqueraded so FortiOS replies through the bridge\n435: - traffic from FortiOS out through `eth0` is masqueraded for breakout\n436: \n437: IPv6 forwarding is enabled in the container and equivalent IPv6 NAT rules are\n438: installed. The bridge is allowed through QEMU bridge configuration with\n439: `/etc/qemu/bridge.conf`.\n440: \n441: In this mode the TFTP server runs in the container's normal namespace. UDP DNAT\n442: lets FortiOS reach it through the host-forwarded management path.\n443: \n444: This mode keeps Containerlab's management network connected to the container,\n445: not directly to FortiOS. It is easier to reason about as NAT/port-forwarding,\n446: but it means all management services except serial are forwarded through the\n447: container.\n448: \n449: ### Passthrough Mode\n450: \n451: `PassthroughRedirect` is the default mode. It makes FortiGate `port1` appear to\n452: participate directly in the Containerlab management network.\n453: \n454: QEMU attaches `port1` with a tap:\n455: \n456: ```text\n457: -netdev tap,ifname=tap0,id=p00,script=/etc/tc-tap-mgmt-ifup,downscript=no\n458: ```\n459: \n460: The generated ifup script:\n461: \n462: - brings up `tap0`\n463: - disables IPv6 addresses on `tap0` to avoid container-originated IPv6 chatter\n464: - adds `clsact` qdiscs to `eth0`, `tap0`, and the redirect veth\n465: - passes TCP ports `5000-5007` so serial consoles stay on the container\n466: - mirrors ARP from `eth0` to `tap0`\n467: - redirects most ingress `eth0` traffic to `tap0`\n468: - redirects ingress `tap0` traffic back to `eth0`\n469: - changes container `eth0` to the VM management MAC\n470: \n471: Passthrough mode also creates a private namespace named `fakehost` with a veth\n472: pair:\n473: \n474: ```text\n475: root namespace: RA\n476: fakehost namespace: FA\n477: ```\n478: \n479: The namespace exists so launcher-owned services, currently TFTP, can still live\n480: \"beside\" the VM even though normal management traffic is redirected straight\n481: between the Containerlab management network and the VM tap.\n482: \n483: The namespace starts with a temporary address so services can bind before QEMU\n484: calls the tap ifup script. During ifup, the temporary address is replaced with\n485: the management gateway address that FortiOS expects. `tc flower` rules redirect\n486: selected service ports from the VM to the namespace and rewrite Ethernet\n487: destinations so the veth path works:\n488: \n489: - VM -> namespace traffic is matched on protocol, destination port, and gateway\n490:   IP, then redirected from `tap0` to `RA`\n491: - namespace -> VM return traffic is matched on source port and FortiGate\n492:   management IP, then redirected back to `tap0` with the VM MAC\n493: \n494: The TFTP server runs inside `fakehost` in passthrough mode, with a fixed TID\n495: port range so the flower rules can match both the initial TFTP request and\n496: server-selected data ports.\n497: \n498: Passthrough gives the most natural Containerlab management behavior, but it is\n499: the most fragile path: MAC rewriting, tap setup timing, namespace addressing,\n500: and tc filter order all need to line up before license restore can work.\n\n(End of file - total 500 lines)\n</content>",
    "title": "source/head/fortinet/fortigate/docker/README.md",
    "metadata": {
      "preview": "# Shared FortiOS Launcher Internals\n\nThe shared launcher source is in [`../../common`](../../common). The\nFortiGate and FortiProxy Docker Makefiles stage that package with a small\nproduct-specific `launch.py` wrapper. The public FortiGate API is documented in\n[`../README.md`](../README.md). This file documents how the launcher works\ninside the vrnetlab image and why some of the implementation looks unusual.\n\nThe launcher is built around serial-console automation. FortiOS does not expose\na stable early-boot API for the work this image needs to perform, so bootstrap\nis modeled as three layers:\n\n```text\nserial connection -> Terminal -> FOSCliDriver -> FOSCommander -> Features\n```\n\n## Three Layer Model\n\n### Terminal\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/fortigate/docker/README.md",
        "text": "# Shared FortiOS Launcher Internals\n\nThe shared launcher source is in [`../../common`](../../common). The\nFortiGate and FortiProxy Docker Makefiles stage that package with a small\nproduct-specific `launch.py` wrapper. The public FortiGate API is documented in\n[`../README.md`](../README.md). This file documents how the launcher works\ninside the vrnetlab image and why some of the implementation looks unusual.\n\nThe launcher is built around serial-console automation. FortiOS does not expose\na stable early-boot API for the work this image needs to perform, so bootstrap\nis modeled as three layers:\n\n```text\nserial connection -> Terminal -> FOSCliDriver -> FOSCommander -> Features\n```\n\n## Three Layer Model\n\n### Terminal\n\n`terminal.py` is the lowest layer. It wraps the vrnetlab telnet console and\nprovides buffered reads, regex matching, writes, and output suppression.\n\nImportant behavior:\n\n- `Terminal.expect()` keeps unmatched bytes in an internal buffer across calls.\n  FortiOS prompts and banners often arrive fragmented, so callers must not\n  assume one read equals one logical event.\n- A terminal-owned reader thread continuously drains the serial connection into\n  a byte-counted, thread-safe queue. `Terminal.expect()` reads from that queue\n  instead of making serial syscalls directly, so CLI state handling is not paced\n  by each console read attempt. The FortiOS scrapli console exposes a blocking\n  read for this thread; nonblocking eager reads remain only as a fallback for\n  simpler connection wrappers.\n- `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n  writing to the serial connection directly. The writer preserves write order\n  and sends one queued chunk at a time, so commander/driver state handling is\n  not paced by each scrapli write call.\n- `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n  view of the matched prefix or, on timeout, the entire unmatched buffer.\n  Inspecting timeout `Data` leaves those bytes buffered so later input can\n  complete a partial token. Calling `discard()` explicitly consumes the view.\n  `received_new_data` distinguishes fresh input from another inspection of the\n  same retained bytes, so idle waits still advance the driver's stall timer.\n- When multiple regexes match buffered output, the match that ends earliest\n  wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n- Matched bytes are consumed from the buffer; bytes after the match stay queued\n  for the next state parse.\n- Timeout bytes are not consumed automatically. A command, feature, or commander\n  inspection path must call `data.discard(...)` if it has assigned meaning to\n  those bytes. Otherwise the bytes stay in the terminal buffer and can be\n  matched again when later output completes a prompt or state.\n- Retained terminal data is bounded by `FTNT_TERMINAL_BUFFER_LIMIT_BYTES`, which\n  defaults to 1 MiB. If the buffer grows beyond that limit, bootstrap fails\n  instead of truncating data, because oversized retained output means some layer\n  failed to consume bytes it understood.\n- The same limit bounds unread data in the reader queue and unsent data in the\n  writer queue. When queued serial data reaches the limit, the reader or writer\n  thread waits until the corresponding consumer drains queue bytes.\n- `suppress_output()` temporarily prevents machine-readable commands such as\n  `show` and `get system status` from being mirrored to the visible serial log,\n  while still keeping their output available to the parser.\n- `wait_write()` is legacy-compatible convenience glue. New bootstrap logic\n  generally goes through `FOSCommander`, but `Terminal` still owns the raw IO\n  primitives.\n\nThe terminal layer does not understand FortiOS. It only knows bytes, regexes,\nand writes.\n\n### State Parsing\n\n`fos_cli_driver.py` translates terminal output into `FOSCliState` events. It\nowns login and interactive prompt handling:\n\n- username prompt\n- password prompt\n- first-login password change\n- current-password prompt after admin password changes\n- credential rejection and blank-password fallback\n- `Welcome!`\n- command prompt\n- reboot and shutdown messages\n- license failure\n- `--More--` pagination\n- unknown output and timeout recovery\n\nThe driver runs in short spins. Each spin reads a state from `Terminal.expect()`,\nhandles login/pager responses itself, and then tells `FOSCommander` what state\nwas observed. Command dispatch is deliberately not done directly in the driver;\nthe driver only answers FortiOS protocol prompts and feeds state to the\ndispatcher.\n\nThe driver does not decide whether unknown or prompt-echo output is meaningful.\nIt passes `Data` to the commander. If the downstream command, feature, or\ncommander inspection path discards it, the terminal buffer is updated through\nthe `Data` object. If it is not discarded, the bytes remain buffered.\n\nThere are two prompt-pattern phases:\n\n- Before license and hostname changes, prompt matching accepts broad bootstrap\n  hostnames because FortiOS can rename itself or switch to a licensed serial\n  style.\n- After hostname setup, the driver narrows login and command prompt patterns to\n  the configured node hostname.\n\nUnknown output is treated as a stall only after it keeps arriving without a\nknown state. The driver sends a small number of newlines to recover prompts,\nthen fails if FortiOS stays unparseable.\n\n### Command Dispatcher\n\n`fos_commander.py` schedules feature commands. It is the only layer that knows\nwhich bootstrap feature is active and which command is in flight.\n\nCommands are represented by:\n\n- `CommandSpec`: one FortiOS CLI line plus execution flags\n- `ConfigBlock`: emits `config <scope>`, child commands, and `end`\n- `EditBlock`: emits `edit <name>`, child commands, and `next`\n- `CommandSequence`: emits child commands without config framing\n\nPlain string commands are automatically wrapped in a default `CommandSpec`\nwhen submitted directly or used inside any command container. Use an explicit\n`CommandSpec` only when a command needs non-default execution flags.\n\n`CommandSpec` intentionally has no separate name field. The command line is the\nidentity, and feature state machines track phase when they need context.\n\nThe dispatcher sends one command at a time and waits for an appropriate state\nbefore continuing. By default, a command completes at the next command prompt.\nSome commands override completion states, for example confirmation prompts or\nreboot messages.\n\nScope-closing commands (`next` and `end`) always capture their output and check\nfor `Command fail. Return code <number>`, including builds that append a period\nafter the code. A closing failure stops the feature before completion callbacks\nor further commands, even when `fail_on_error=False`. It follows the bootstrap\nerror policy: abort normally, or skip the failed feature when\n`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\nindividual `set` commands, which can deliberately tolerate unsupported fields.\n\nSession loss is explicit. Each command carries a `SessionLossAction`:\n\n- `RESTART_BLOCK`: replay the current block from the start\n- `COMPLETE_BLOCK`: treat the block as complete\n- `CONTINUE`: do not replay the disruptive command\n- `VALIDATE`: reserve for commands that need post-loss validation\n- `FAIL`: report failure through the configured bootstrap error policy\n\nThis matters because commands such as license restore and password updates can\ndrop the active admin session. Replaying them blindly can corrupt state or loop.\n\nUnexpected prompt context changes call `Feature.on_context_loss(attempt)`.\nThe feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\ncommands that allow session-loss replay also allow context-loss replay; commands\nwith another session-loss policy decline context-loss replay unless explicitly\nconfigured otherwise. Context loss does not invoke session-loss callbacks, since\nthose may commit credential or licensing transitions.\n\nThe commander allows one recovery per command position within a submitted block,\nshared between context loss and session loss. Recovery replays the block's scope\nopeners and commands. If necessary, the commander sends one `abort` to restore\nthe block's initial prompt context before replay. A repeated loss at the same\ncommand or failure to restore that context follows the bootstrap error policy.\nThe allowance resets when the feature submits a new block. Cleanup commands also\nhave one session-loss retry. Attempts expose `retry_count` and the prompt context\nbefore and after execution so features can make their recovery decision.\n\nThe dispatcher also manages cleanup actions and standard-output contexts.\nFeatures can request console output mode `standard` for machine-readable output;\nthe dispatcher detects the current console mode, changes it only when needed,\nand restores `more` after the feature completes.\n\n## Output Handling\n\nAll CLI output passed into `FOSCommander` is `terminal.Data`. The commander does\nnot accept raw bytes and does not own output buffering. The output path is:\n\n```text\nTerminal.expect() -> Data -> FOSCliDriver -> FOSCommander\n```\n\nWhen output arrives while a command is in flight, the commander offers it in\nthis order:\n\n```text\nCommandAttempt.on_output(data)\nFeature.on_output(data)\nFOSCommander._inspect_output(data)\n```\n\nThe first layer that understands the data consumes it by calling\n`data.discard(...)`. Consumption has two effects:\n\n- the consumer records whatever state it needs, such as command output\n- the terminal buffer discards the consumed bytes when the `Data` object is a\n  timeout view into retained terminal data\n\nCommand output capture belongs to `CommandAttempt`. If a command has\n`capture_output=True`, `CommandAttempt.on_output(data)` appends\n`bytes(data)` to `command.output` and discards those bytes. When the command\nfinishes, the feature receives the completed command:\n\n```text\non_command_executed(command, state)\n```\n\nFeatures inspect `command.spec` to know which command completed and\n`bytes(command.output)` to inspect captured output. Features should not\nreconstruct command output from commander state.\n\n`Feature.on_output(data)` remains for out-of-band streams. For example, a\nfeature may start a debug command and wait for asynchronous data that is not the\nnormal command completion transcript. If the feature recognizes that data, it\nmust call `data.discard(...)` before returning true. If it does not recognize\nthe data, it returns false and the commander can inspect it or leave it buffered.\n\nPrompt echo uses the same path. `CMD_PROMPT_ECHO` is not special-cased with a\nseparate parser in the commander. The driver passes the prompt-echo `Data` to\n`FOSCommander.on_prompt_echo()`, which calls `on_output(data)`. If any layer\ndiscards the data, no recovery newline is sent. If no layer consumes it, the\ncommander sends a newline to request a clean prompt.\n\nThis is the critical invariant: output that has been assigned meaning must be\ndiscarded through `Data`; output that is not understood must remain buffered so\nit can be completed by later serial data.\n\nThe retained terminal buffer has a hard upper bound. The default is 1 MiB, set\nwith `FTNT_TERMINAL_BUFFER_LIMIT_BYTES` when a larger diagnostic window is needed.\nThe limit is intentionally enforced as an error rather than a ring buffer: if\nretained data grows without being consumed, the command/feature/commander stack\nhas lost ownership of some output and continuing would risk replaying stale\nbytes into later state decisions.\n\n## Feature Architecture\n\nBootstrap work is split into feature objects under `common/features/`. A feature has a\nname, lifecycle hooks, optional file-watch integration, and zero or more command\nblocks.\n\nThe core lifecycle is:\n\n```text\nbegin_activation()\n promactivate()\non_command_dispatched(attempt)\non_output(output)\non_command_executed(command, state)\non_block_complete()\non_session_loss(attempt)\non_context_loss(attempt)\nmark_completed()\n```\n\nStatic command features subclass `StaticFeature`; they submit a fixed list of\nblocks and complete after the last block. Dynamic features subclass `Feature`\nand submit follow-up blocks based on command output or timer ticks.\n\nCurrent bootstrap stages are:\n\n- `disk-format`: formats additional disks after the first FortiGate log disk\n- `admin`: disables password policy, creates/updates the desired admin, then\n  logs out and waits for console authentication before later stages run\n- `image-info`: reads `get system status` once and stores the parsed\n  platform, major, minor, patch, and build on `vm.fos_version` for later\n  features\n- `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n  the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n- `management`: configures `port1`, FortiGuard interface selection, and the\n  management route for static management addressing\n- `bootstrap-dns`: temporarily sets DNS for license/bootstrap reachability\n- `fortiguard-hooks`: applies the optional `DIAG_2`/`DIAG_1` guard commands and\n  the FortiGuard settings used when the hooks are enabled\n- `setup-license`: restores `/tftpboot/appliance.lic` over TFTP and handles reboot\n- `default-config`: applies launcher-owned defaults such as `admin-scp` and the\n  final hostname\n- `management-after-license`: reapplies management after license restore because\n  FortiOS can remove routes or drop sessions when registration state changes\n- `fortiguard-hooks-after-license`: reapplies the FortiGuard hook settings after\n  the license reboot whenever `FTNT_FORTIGUARD_HOOKS` is enabled\n- `license-validation`: accepts `Valid`, and accepts `Grace Period` unless\n  `FTNT_WAIT_FOR_VALID_LICENSE=true`; `Pending` and strict-mode `Grace Period`\n  are retried until the configured timeout\n- `management-vrf`: moves management into VRF 1 when supported, or narrows\n  the management route on FortiProxy\n- `undo-bootstrap-dns`: removes the temporary bootstrap DNS settings\n- `fortitoken-provisioning`: after a license becomes `VALID`, polls for\n  license-provisioned FortiTokens for up to 15 seconds\n- `capture-config`: records a clean baseline and later services `/get-config`\n  runtime captures\n- `pki-certificates`: installs CA, local, remote, and CRL objects from\n  `FTNT_PKI_*` path variables; failed config installs fall back to TFTP where\n  supported, warning on successful fallback and failing bootstrap if both\n  methods fail\n- `startup-config`: imports the user-supplied startup config\n\n`FeatureFileWatcher` polls watched feature paths after bootstrap. Today the\nmain runtime feature is config capture: writing a request to `/get-config`\nenqueues the capture feature after the launcher reconnects to the serial\nconsole. A trigger created *or modified* between polls is a new request\n(`on_file_detected` and `on_file_modified` share one handler), so a client\nthat re-writes the trigger while an earlier capture is still running is not\nsilently dropped. Each request is answered by one JSON status record per\nrequest id under `/config/get-config.status.d/<id>.json`\n(`{\"id\", \"status\": pending|success|busy|error, \"output\"?, \"error\"?}`),\nwritten atomically; records older than 120 s are swept when a new request\nis accepted. An empty trigger (a human `touch`) still works and gets a\ngenerated id. See the `fortigate/README.md` \"Saving Config\" section.\n\nBootstrap feature errors are fatal by default. With\n`FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, a failed feature is logged and skipped\nwhen FortiOS is back at a command prompt, and the remaining startup features\ncontinue. This is best effort: commands that already ran are not undone, and a\nrun with skipped features is not reported healthy. Credential fallback remains\nunresolved until the desired credentials authenticate successfully; unresolved\nfallback also keeps the VM unhealthy. After a desired-password rejection, the\nlauncher retries the last accepted credentials once for that login regardless\nof the bootstrap error policy, while retaining the desired\ncredentials for later logins. It does not replay an admin password-change block\nafter FortiOS has committed it. If the CLI is at an interactive prompt or both\ncredential attempts fail, bootstrap halts, keeps the VM running, and releases\nthe launcher's serial Telnet connection for manual repair. Runtime feature\nfailures, such as a `/get-config` request, remain request errors and do not\nchange this bootstrap policy.\n\nThe feature architecture is intentionally serial. FortiOS CLI state is global,\nthe console has one prompt stream, and several operations can reboot or remove\nadmin sessions. Parallel feature execution would make recovery ambiguous.\n\n## Design Quirks\n\n### Password handling is deliberately conservative\n\nFortiOS versions differ in default credential behavior. Some accept the default\npassword, some require first-login password changes, and some older paths accept\na blank default password first. The driver keeps separate bootstrap and desired\ncredentials so it can answer prompts with the password that is valid at that\nmoment.\n\nThe desired credentials are activated after the admin edit commits. Password\ncommand output is checked for FortiOS command failures. After closing the admin\nconfiguration, the feature sends `exit` and waits for a successful login and CLI\nprompt before completing. A logout during the commit also activates the new\ncredentials without replaying the password change. The driver first tries the\ndesired credentials. If FortiOS rejects\nthem, it retries immediately with the previously accepted credentials, without\nreplacing the desired credentials used for later logins.\n\n### Prompt patterns change during bootstrap\n\nLicense installation and hostname changes can alter prompt text. During license\nrestore the driver broadens prompt matching; after `set hostname`, it narrows\npatterns to the configured hostname. This is why prompt handling lives in the\ndriver rather than directly in features.\n\n### Console pagination is not globally disabled forever\n\nMachine-readable commands need unpaginated output, but interactive users expect\nFortiOS's normal paginated console. The commander temporarily switches to\n`standard` output for captures and polls, then restores `more` if it changed\nthe setting.\n\n### Config capture is delta-based\n\nThe launcher captures a baseline before user startup config. Later `/get-config`\ncaptures run `show`, clean terminal artifacts, parse config/edit blocks, and\nwrite only changes to `/config/current.conf`.\n\nEncrypted fields are noisy because FortiOS can emit different `ENC` values for\nthe same effective secret. The diff code can ignore ENC-only changes for\nexisting entries when configured, but it still retains encrypted fields for new\nentries or entries with other body changes.\n\n### Feature names are workflow controls, not command labels\n\nFeature names are used for logging, debug cutoffs, and undo stages. Individual\ncommands are identified by their CLI line. When a workflow needs to distinguish\nsteps, it tracks its own phase instead of attaching synthetic names to commands.\n\n## Gotchas And Required Hoop-Jumps\n\n- Bootstrap must run through the serial console. SSH is not reliable until\n  credentials, management, license state, and prompt patterns settle.\n- License restore can reboot FortiOS and can remove the active admin session.\n  The `setup-license` feature marks those commands as non-replayable and waits\n  for the next prompt instead.\n- Management configuration is applied more than once. License registration can\n  disturb routes and sessions, so `management-after-license` repairs management\n  before license polling.\n- FortiProxy does not support interface VRFs in the same way FortiGate does.\n  `management-vrf` detects `set vrf 1` failures and falls back to a\n  management-gateway route destination instead of installing a broad default\n  route.\n- TFTP needs special handling in both management modes. The license file is\n  restored from `/tftpboot/appliance.lic`; the VM must be able to reach the\n  launcher TFTP service from its management interface during bootstrap.\n- The QEMU management MAC can come from snapshot metadata or vrnetlab's generated\n  MAC. In passthrough mode the container `eth0` MAC is changed to the VM\n  management MAC so redirected management traffic looks consistent.\n- The launcher writes files inside `/config` and the node config mount. These\n  files are part of runtime behavior, not source artifacts.\n- The Makefile copies only regular files from `../../common` into this directory\n  during image build. Python cache directories under `common/` must not enter\n  the Docker build context as copied launcher assets.\n\n## Management Networking\n\nThe management strategy is selected before the VM is created. Both strategies\nimplement `NetMgmtStrategy`, which supplies QEMU `-netdev` arguments and writes\nstrategy-specific host/container networking.\n\n### Host-Forwarded Mode\n\n`HostForwardedBridge` is used when management passthrough is disabled. It\ncreates an internal bridge named `br-mgmt` and gives the FortiGate a point to\npoint management network:\n\n```text\ncontainer bridge: 172.31.255.29/30, 200::/127\nFortiGate port1: 172.31.255.30/30, 200::1/127\n```\n\nQEMU attaches `port1` with:\n\n```text\n-netdev bridge,br=br-mgmt,id=p00\n```\n\nThe container installs NAT rules:\n\n- inbound TCP on `eth0`, except serial port `5000`, is DNATed to the FortiGate\n  management address\n- inbound UDP on `eth0` is DNATed to the FortiGate management address\n- traffic leaving `br-mgmt` is masqueraded so FortiOS replies through the bridge\n- traffic from FortiOS out through `eth0` is masqueraded for breakout\n\nIPv6 forwarding is enabled in the container and equivalent IPv6 NAT rules are\ninstalled. The bridge is allowed through QEMU bridge configuration with\n`/etc/qemu/bridge.conf`.\n\nIn this mode the TFTP server runs in the container's normal namespace. UDP DNAT\nlets FortiOS reach it through the host-forwarded management path.\n\nThis mode keeps Containerlab's management network connected to the container,\nnot directly to FortiOS. It is easier to reason about as NAT/port-forwarding,\nbut it means all management services except serial are forwarded through the\ncontainer.\n\n### Passthrough Mode\n\n`PassthroughRedirect` is the default mode. It makes FortiGate `port1` appear to\nparticipate directly in the Containerlab management network.\n\nQEMU attaches `port1` with a tap:\n\n```text\n-netdev tap,ifname=tap0,id=p00,script=/etc/tc-tap-mgmt-ifup,downscript=no\n```\n\nThe generated ifup script:\n\n- brings up `tap0`\n- disables IPv6 addresses on `tap0` to avoid container-originated IPv6 chatter\n- adds `clsact` qdiscs to `eth0`, `tap0`, and the redirect veth\n- passes TCP ports `5000-5007` so serial consoles stay on the container\n- mirrors ARP from `eth0` to `tap0`\n- redirects most ingress `eth0` traffic to `tap0`\n- redirects ingress `tap0` traffic back to `eth0`\n- changes container `eth0` to the VM management MAC\n\nPassthrough mode also creates a private namespace named `fakehost` with a veth\npair:\n\n```text\nroot namespace: RA\nfakehost namespace: FA\n```\n\nThe namespace exists so launcher-owned services, currently TFTP, can still live\n\"beside\" the VM even though normal management traffic is redirected straight\nbetween the Containerlab management network and the VM tap.\n\nThe namespace starts with a temporary address so services can bind before QEMU\ncalls the tap ifup script. During ifup, the temporary address is replaced with\nthe management gateway address that FortiOS expects. `tc flower` rules redirect\nselected service ports from the VM to the namespace and rewrite Ethernet\ndestinations so the veth path works:\n\n- VM -> namespace traffic is matched on protocol, destination port, and gateway\n  IP, then redirected from `tap0` to `RA`\n- namespace -> VM return traffic is matched on source port and FortiGate\n  management IP, then redirected back to `tap0` with the VM MAC\n\nThe TFTP server runs inside `fakehost` in passthrough mode, with a fixed TID\nport range so the flower rules can match both the initial TFTP request and\nserver-selected data ports.\n\nPassthrough gives the most natural Containerlab management behavior, but it is\nthe most fragile path: MAC rewriting, tap setup timing, namespace addressing,\nand tc filter order all need to line up before license restore can work.",
        "lineStart": 1,
        "lineEnd": 500,
        "totalLines": 500,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716563976,
      "end": 1793716563983
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d6b012001WmTQpaR0OA12hE",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6a6f5001olbbGFgBgts46C",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 47514,
    "input": 7262,
    "output": 46,
    "reasoning": 14,
    "cache": {
      "read": 40192,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d6a6f5001olbbGFgBgts46C",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716561653,
    "completed": 1793716563989
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 47514,
    "input": 7262,
    "output": 46,
    "reasoning": 14,
    "cache": {
      "read": 40192,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 30
step-start
{
  "type": "step-start",
  "id": "prt_1a1d6b8d7001lILCDvcH9Ru9EX",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6b01c001HjcQGO1Ola6aLQ"
}
Reasoning
I've now read all the changed files. Let me check the diff to make sure I know what changed vs. base for each file — I read the full diff earlier (per the summary). But I need to be careful about which findings are attributable to the PR.

Let me now think about what findings to report. Let me recall key parts of the diff from the prior summary:

Changed files:
1. cli_commands.py — ContextLossAction, CommandSpec.context_loss/continuation, closes_scope, CommandAttempt, flatten_commands/_flatten_quoted_lines, CleanupAction
2. common.py — TRACE_LEVEL, FOSCliState (KERNEL_PANIC), BOOTSTRAP_HOSTNAME_REGEX, PROMPT_CONTEXT_REGEX, patterns
3. fos_commander.py — the scheduler
4. fos_cli_driver.py — stall detection, KernelPanicError, credential recovery
5. launch.py — KernelPanicError handling
6. terminal.py — Data, buffer, discard callback
7. features/* — base, credentials, license, startup_config, pki
8. READMEs
9. tests — 5 files (2 modified, 3 added)

I should check the diff for specific changes to know what's new vs pre-existing. My prior analysis found mostly resolved concerns. Let me now do a final targeted analysis for real findings.

Candidate findings to consider:

A. `features/startup_config.py` filter message mentions `FTNT_FORTIGUARD_HOOKS` but the env checked is via `has_env("FOS_FORTIGUARD_HOOKS")`. The warning message text at line 41-44 says "FTNT_FORTIGUARD_HOOKS is present with FTNT_DNS_PRIMARY..." — but `has_env` checks FOS_ name first, then FTNT_ alias. So the message could be misleading if user set FOS_FORTIGUARD_HOOKS. Minor — message says FTNT names which are "the documented environment interface" per README. Not a finding really. Actually the check is on FOS_FORTIGUARD_HOOKS with alias FTNT_FORTIGUARD_HOOKS. The log message names FTNT spellings. README documents FTNT_ names as the public interface, and says "Existing environment variable names remain accepted during the compatibility period." So logging the documented name is fine.

B. `SetValue.flatten()` — when `validate_prompt=True` (default) and single line, `_flatten_quoted_lines` produces completion_states=() and expected=CMD_PROMPT. Fine.

Hmm — one thing to check in `_flatten_quoted_lines`: for multi-line, the last line's `expected_completion_state` is CMD_PROMPT only if validate_prompt. But wait — for a SetValue inside a config block, after the final line, FortiOS returns to the continuation-context prompt (e.g., `(edit)` prompt), not the top-level prompt. That's fine — CMD_PROMPT matches any context.

C. `startup_config.py` `_startup_config_commands`: potential issue — a line inside a pending (unterminated) quoted string that starts with `#` is preserved as data (good, per comment). But a comment line *between* a continuation? E.g. after an unterminated quote, a line starting with `#` is appended to pending — correct since it's part of the quoted string.

But what about: pending is empty, line starts with `#` → skipped. Good.

Potential subtle issue: `elif character == quote: quote = None` — when quote is None and character is `'` or `"`, we open a quote. But if `quote is None and character in {"'", '"'}` and the previous character was a backslash... escaped handles that. OK.

Edge: what about a line where `escaped` is True at line end AND quote is None — continuation. What about escaped=True at end and quote set (inside quote)? e.g. `"abc\` — quote = '"', escaped=True → pending. Next line continues quote. Correct.

D. `parse_startup_config` — `next`/`end` matching only when line == "next"/"end" exactly after strip of the first line only... wait: for pending commands (multi-line), `yield "\n".join(pending)` — the joined command starts with the lstripped first line. So `line.startswith("config ")` etc. work. But a multi-line quoted command whose first token is "config ..."? That would be a `config` command with a quoted value spanning lines — would be treated as ConfigBlock with value containing newlines. Then `flatten_commands` splits it into multiple lines... `ConfigBlock.flatten()` → `flatten_commands(self.open_line)` → open_line contains "\n" → `_flatten_quoted_lines`. But the first line is `config system dns` and the rest are continuation lines of the config command?? That's malformed input anyway ("config" with quoted multiline value is nonsense). The parser would then treat "next"/"end" within. Not a real concern; malformed configs raise errors.

Hmm wait, actually there IS an issue: `parse_startup_config` only strips whitespace from the first line (`line.lstrip()` when pending is empty). For `elif line == "next"`, a `next` line with trailing whitespace: the last pending line gets `.rstrip()` (line 77), so "next  " → "next". But " next" with leading spaces when not in a quote? Leading whitespace on a continuation-only... no wait: if pending is empty and line is " next" (leading spaces), it gets lstripped → "next". Good. If line is inside a quote, it's data. Good.

But what about `end ` with trailing comment? Not supported; treated as a command. Fine.

E. Now the bigger picture — I found no major correctness issues in my analysis. Let me now scan for things worth reporting:

1. **`terminal.py` `_match` performance**: `re.search(pattern, self._buffer)` on a bytearray per pattern per read. With `b"long" * 2048` payloads and buffer up to 1 MiB, and ~18 state patterns scanned per read... Actually `_next_state` calls expect with all state patterns (~18 regexes). Each `_match` call runs 18 regexes over the buffer. The buffer is consumed on match, so normally small. On timeout with retained data up to 1 MiB, each new chunk re-runs all regexes over the full buffer — O(n·m) per byte. This is pre-existing behavior? Need to check the diff — was _match/enforce_buffer_limit part of this PR? The terminal.py rewrite with Data/discard is part of this PR (the whole Terminal class seems new/rewritten). Hmm. The complexity: for a 1 MiB retained buffer and 18 patterns, each read of a small chunk re-searches everything: this is the classic incremental-matching concern, but patterns are line-anchored mostly and FortiOS output is bounded. Given EXPECT_TIMEOUT_SECONDS loops, each expect call re-matches the full buffer once per incoming chunk. Worst case: continuous unknown output at serial speed (~115200 baud ≈ 11 KB/s) with buffer growing to 1 MiB — after ~90s, each chunk triggers 18 full-buffer regex searches over ~1 MiB ≈ manageable but O(n²) total ≈ 18 · (1 MiB)² / chunk ≈ heavy. Realistically the buffer only grows when nothing matches, and unknown output triggers stall recovery after UNKNOWN_STALL_SECONDS. This is speculative; the buffer limit makes it bounded at 1 MiB. I'd rate it P4 at most, or skip. Actually there's a real point: `_match` is called after every chunk, scanning the entire buffer for each of up to 18 patterns — but re.search on a 1 MiB bytearray for a line-anchored regex is fast (µs–ms). Total bytes processed bounded by buffer_limit per expect. I'll skip or make it a P4 note? It's speculative; the design is bounded. Skip.

2. **`terminal.py` `expect` re-checks deadline after `get` returns empty**: when `data` is empty (queue drained but not closed), it checks `if deadline is not None and time.monotonic() >= deadline` → return timeout. But if data is empty and deadline hasn't passed, the `while result is None` loop calls `self._read_queue.get(remaining)` again — busy-wait? No: `get` blocks until deadline. Fine.

3. **`_discard_prefix` safety**: refuses non-prefix. Good.

4. **`fos_cli_driver.py` `set_prompt_patterns`**: `name_pattern` bytes → `re.escape(...)`? It does `re.escape(name_pattern.encode())` for str. For bytes input (BOOTSTRAP_HOSTNAME_REGEX is already a compiled pattern? No — it's a bytes regex literal `rb"..."`? Let me recall: BOOTSTRAP_HOSTNAME_REGEX is passed to set_prompt_patterns. In license.py `self.vm.driver.set_prompt_patterns(BOOTSTRAP_HOSTNAME_REGEX)`. Is BOOTSTRAP_HOSTNAME_REGEX a bytes pattern or compiled? From common.py (92 lines), `BOOTSTRAP_HOSTNAME_REGEX = rb"(?m)^(?:(?:...)|...)..."`? If it's a compiled regex, `re.escape(compiled)` would produce something weird. Need to check common.py content. I read it but the summary only summarized. Let me re-read common.py to verify.

5. **` fos_commander.py`** — I read all 687 lines but the summary doesn't include detailed line numbers. For the final report I need precise line anchors. I'll need to re-read portions of fos_commander.py to cite lines. Since findings list may be small, I need accurate anchors for whatever I report.

Let me re-read common.py and key parts of fos_commander.py to pin down line numbers for any findings.

Actually, let me think about what findings I actually have at this point. My prior extensive analysis resolved all four concerns as non-issues. So the findings list may be quite small. Let me do a final sweep for genuine issues:

Potential findings:

F1. `features/license.py` `on_command_executed` — `self._check_for_failure(command)` runs for every command executed while the feature is active, including unrelated? SetLicense only submits its own commands, so fine.

F2. `WaitForLicenseValidation.on_command_executed` — it processes EVERY command executed while active, including commands from other features? `on_command_executed` is a feature callback — the commander calls it for commands of that feature only? Need to verify in fos_commander.py. If the commander broadcasts on_command_executed to all features, then `_license_status(output)` on other features' commands could misfire. Let me check fos_commander.py: how on_command_executed is invoked. From my prior read: the commander calls `feature.on_command_executed(attempt, state)` for the feature that owns the block. I believe it's targeted. Need to verify.

F3. `launch.py` line 299-303: `disk_specs = get_env("FOS_DISK_SPECS", "").split(",")` — but README documents `FTNT_DISK_SPECS`. `get_env("FOS_DISK_SPECS")` aliases FTNT_DISK_SPECS (since name starts with FOS_). Good — env.py handles it. And `get_env("FTNT_DNS_PROTOCOL", "cleartext")` at line 239 — README documents `FTNT_DNS_PROTOCOL` — fine.

F4. `exit_on_bootstrap_error` uses `get_env("FOS_EXIT_ON_BOOTSTRAP_ERROR", "true")` → alias FTNT_EXIT_ON_BOOTSTRAP_ERROR. Good.

F5. `apply_debug_feature_cutoff` — `FOS_DEBUG_FEATURE` → FTNT_DEBUG_FEATURE. Good.

F6. In `test_common_stack_boundaries.py` `make_stack`: on failure paths, `finally: if not connection.closed: terminal.close()` — in `test_expected_completion_prompt_mismatch_raises_from_serial_result` the finally only calls terminal.close() without the connection.closed check — minor.

F7. `state_case` in boundaries: `completion = (FOSCliState.CMD_PROMPT,)` duplicated in both if branches (lines 105-108) — the first branch for CREDENTIAL_REJECTED/PROVIDE_USERNAME and second for CREDENTIAL_ACCEPTED/SESSION_LOST/CMD_PROMPT_ECHO both set CMD_PROMPT; could merge. Minor P4.

F8. `fos_commander.py` — the `_cleanup_retries` id(spec) issue: P4.

F9. Documentation: README states `FTNT_DNS_PRIMARY`/`FTNT_DNS_SECONDARY` — matches env aliases. The startup-config filter warning names FTNT_FORTIGUARD_HOOKS — README documents `FTNT_FORTIGUARD_HOOKS`? The README env table doesn't list FTNT_FORTIGUARD_HOOKS! Let me check: README lists CLAB_MGMT_PASSTHROUGH, FTNT_DISK_SPECS, FTNT_DEBUG_FEATURE, FTNT_DNS_PRIMARY, FTNT_DNS_SECONDARY, FTNT_DNS_PROTOCOL, FTNT_EXIT_ON_BOOTSTRAP_ERROR, FTNT_HEALTHCHECK_STALL_SECONDS, FTNT_HEARTBEAT_FILE, FTNT_LOG_LICENSE_STATUS_OUTPUT, FTNT_LICENSE_STATUS_TIMEOUT_SECONDS, FTNT_LOG_LEVEL, FTNT_NO_ENC_CONFIG, FTNT_ONBOARDING, FTNT_SKIP_PRODUCT_CHECK, FTNT_WAIT_FOR_VALID_LICENSE, FTNT_PRODUCT_VERSION, FTNT_PKI_*, UUID. `FTNT_FORTIGUARD_HOOKS` is referenced in the Startup Config section (line 181) but not documented in the env table. Is that a pre-existing gap or introduced by this PR? Need the diff to know. `filter_startup_config_blocks` — is this function new in this PR? The diff summary said features/startup_config.py changed. I need to check the diff for startup_config.py. Let me grep the diff.

F10. `fos_cli_driver.py` `_license_failed` is a `@staticmethod` returning None — fine.

F11. `Terminal.close()` ordering: stops reader, closes queues, joins writer then clears buffer then closes connection then joins reader. Reader join(1) may not finish within 1s if blocked in `read_very_eager`... daemon threads, acceptable.

F12. `_read_forever` catches exception → `read_queue.fail(error)` — expect() then raises. Good.

F13. In `Terminal.expect`, `consumed` recomputed via `re.search(regex_list[index], consumed)` — "stable_match" — why? Because `self._buffer` may be a bytearray mutated... they take `consumed = bytes(self._buffer[:match.end()])` then `del self._buffer[:match.end()]`, then re-run the regex on the consumed bytes to get a match object that isn't tied to the mutated buffer. That's correct but re-runs the regex. Fine.

F14. `wait_write` — legacy; the `hold` loop writes `\r` and sleeps 10s inside... not changed? It's part of terminal.py. Whether pre-existing, need diff.

F15. `fos_commander.py` — I need to double check `_validate_completion` and `_complete_inflight` details for the scope-failure check and how `on_command_executed` is dispatched. And the `on_output` order: CommandAttempt → Feature → _inspect_output. Let me re-read key sections of fos_commander.py for accuracy (lines ~1-250 and the recovery/validation parts).

Also F16: `SetLicense.on_output` — during "restore"/"restore-confirmed" phases, ANY output (including prompt echo?) is searched for "license install failed". CMD_PROMPT_ECHO output goes through commander.on_output? In `process_state`, prompt echo: `self._commander.on_prompt_echo(output)` → calls on_output path per docs. The prompt echo contains the echoed command `exe restore vmlicense tftp appliance.lic <ip>` — no "license install failed". OK.

But note: `on_output` returns False for non-matching, so output falls through to commander inspection and remains buffered unless something discards. During restore, output not captured... Actually the restore command has capture_output=True, so CommandAttempt captures and discards. Fine.

F17: A real potential issue in `license.py` `on_output`: it searches `output` — a timeout Data view into the retained buffer — for the failure pattern. If found, it raises RuntimeError but never discards. That's fine since we're failing.

F18: `WaitForLicenseValidation.on_command_executed` raises RuntimeError when status invalid — good.

F19: `installPkiCertificates.on_command_executed`: `if not command.spec.capture_output or not COMMAND_FAILURE_PATTERN.search(...)` — only inspects captured commands. Its config commands have capture_output=True. But the TFTP fallback command also capture_output=True. OK. But what about `CommandAttempt.on_output` discarding: captured commands discard bytes as they stream. When command completes, output retained in attempt.output. Fine.

But hmm: `on_command_executed` for PKI fires for the config commands like `config vpn certificate ca` (capture_output=True via config_command) — COMMAND_FAILURE_PATTERN includes "Command fail" — if `edit "name"` fails (e.g. name too long?), _config_failed set → TFTP fallback for kind... but the failure could be for `config` opener, not the item. Then fallback stages the file and runs TFTP import. Reasonable.

But there's a subtlety: `on_command_executed` sets `self._config_failed = True` but does NOT raise — the scope-close check (next/end) still validates return codes: since `config_command` uses fail_on_error=False, and the closing `next`/`end` are checked by the commander — if the edit failed, `next` may return "Command fail. Return code -5"? Actually after a failed `edit`, FortiOS may not enter edit mode, and `next` returns an error → commander raises on closes_scope → bootstrap error policy. Hmm — but the intent was best-effort config attempt with TFTP fallback. If `edit` fails and `next` fails, the commander raises before `on_block_complete` can trigger the fallback. The comment in `_config_item_block` says: "A return-code failure from `next` or `end` is always fatal to the feature: the commander checks scope commits even when fail_on_error is disabled." So they acknowledge this: the fallback only triggers when the scope closes successfully but a `set` command inside failed. OK, by design.

F20: The PKI `_submit_tftp_fallback` uses `self._indexes[kind]:03d` for filename — but `_next_entry` already incremented the index; so the filename is index+1. Cosmetic.

F21: `credentials.py`: `on_command_dispatched` activates desired credentials when "exit" dispatched — before logout, active credentials become desired. Then FortiOS asks for username at login. Driver uses `self._credentials.username` — desired username. Good. But what if FortiOS's `exit` doesn't log out (returns to prompt)? Then `expected_completion_state=PROVIDE_USERNAME` fails → "expected PROVIDE_USERNAME" error. By design (test_logout_must_return_to_login).

F22: In `credentials.py` `on_session_loss` for password command → `SessionLossAction.CONTINUE` and activates desired credentials. But session loss after `set password` — FortiOS logged out mid-password-change? Then password change may not have been committed. CONTINUE skips replay, and the feature continues to "next"/end/exit. Then at login, driver uses desired credentials — if the change wasn't committed, login with desired fails → recovery with previous credentials → feature error "admin-credentials"... but the feature already completed? The relogin block: after password command session loss, current block (system admin config) continues; then `exit` block runs — expects PROVIDE_USERNAME. Wait, after session loss, we're logged out → login prompt. The exit command would be dispatched at a prompt... after reconnect, driver logs in with desired creds → prompt → exit dispatched → logs out → login → relogin with desired. OK, complicated but the tests cover the documented scenarios.

F23: Now — the test `test_common_admin_credentials.py` `make_stack`: `responses[b"oldpass\r"]` pops from `old_password_responses`; when `password` empty... `old_password_responses = [READY]` + maybe ADMIN_PROMPT + LOGIN. Hmm, but wait: when `username != "admin"`, `responses[(username + "\r").encode()] = b"Password:"` — the first login uses "admin\r". OK.

Interesting: in `make_stack`, when `authenticate=False` (login_reply=None): `responses[(password + "\r").encode()] = None` → write gets no response → driver stalls until timeouts... test asserts probe not written. OK.

F24: `test_common_recovery.py` `RecordingFeature.on_session_loss` not overridden — returns default from base (RESTART_BLOCK). OK.

Now, the README documentation check: The startup-config section (README lines 171-176) documents quote continuation behavior — matches implementation. It documents that "Newlines, whitespace, blank lines, and scope keywords inside a quoted value are preserved." — matches. "the closing line must return to a command prompt" — matches `_flatten_quoted_lines` expected CMD_PROMPT. "An unexpected prompt follows the bootstrap error policy." OK.

Does the README document `FTNT_FORTIGUARD_HOOKS` in the env table? No — it's referenced at line 181 ("When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup config is skipped with a warning") and in the feature list of docker README ("fortiguard-hooks: applies the optional DIAG_2/DIAG_1 guard commands and the FortiGuard settings used when the hooks are enabled"). The env table omits FTNT_FORTIGUARD_HOOKS. Is this PR introducing that? The filter function `filter_startup_config_blocks` — likely new in this PR (the diff for startup_config.py). Let me check the diff to confirm what changed in startup_config.py.

I need to look at the diff for specific hunks. Let me grep diff.txt for startup_config and README changes.

Also need to verify: does `has_env("FOS_FORTIGUARD_HOOKS")` exist in other files (fortiguard.py feature)? Yes presumably features/fortiguard.py uses it. Not in changed list, so the env name is established.

If the README's Startup Config section already existed in base with this text, then it's not a PR-introduced gap. The diff will tell.

Let me now check the diff for the relevant hunks: startup_config.py, README.md, terminal.py, cli_commands.py, common.py, fos_commander.py.

Plan:
1. Grep diff.txt for "^diff --git" to list files and find offsets.
2. Read relevant diff hunks.

Then finalize findings with accurate line numbers from head files (I have full contents of most).

Let me do the grep on diff.txt.
All source and test files are now read. Let me confirm which parts of each file are new in this PR by locating the diff hunks, so findings are anchored to introduced changes.
grep · completed

Input

{
  "pattern": "^diff --git",
  "path": "/source",
  "include": "diff.txt"
}

Output

Found 18 matches
/source/diff.txt:
  Line 1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py

  Line 186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py

  Line 217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py

  Line 236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py

  Line 301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py

  Line 323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py

  Line 387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py

  Line 449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py

  Line 861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py

  Line 892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py

  Line 983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md

  Line 1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md

  Line 1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py

  Line 1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py

  Line 1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py

  Line 1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py

  Line 1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py

  Line 1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d75574001HKnPZbYBMAgiiJ",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6b01c001HjcQGO1Ola6aLQ",
  "callID": "call_7bbcc53317ab4a34b6fb636a",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "^diff --git",
      "path": "/source",
      "include": "diff.txt"
    },
    "output": "Found 18 matches\n/source/diff.txt:\n  Line 1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\n\n  Line 186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py\n\n  Line 217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\n\n  Line 236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\n\n  Line 301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\n\n  Line 323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\n\n  Line 387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\n\n  Line 449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\n\n  Line 861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\n\n  Line 892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\n\n  Line 983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\n\n  Line 1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\n\n  Line 1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\n\n  Line 1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\n\n  Line 1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\n\n  Line 1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\n\n  Line 1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\n\n  Line 1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\n",
    "title": "^diff --git",
    "metadata": {
      "matches": 18,
      "truncated": false
    },
    "time": {
      "start": 1793716606330,
      "end": 1793716606346
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d7558c0014iH1ECqHDqv72S",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d6b01c001HjcQGO1Ola6aLQ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 66466,
    "input": 14042,
    "output": 63,
    "reasoning": 4937,
    "cache": {
      "read": 47424,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d6b01c001HjcQGO1Ola6aLQ",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716563996,
    "completed": 1793716606352
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 66466,
    "input": 14042,
    "output": 63,
    "reasoning": 4937,
    "cache": {
      "read": 47424,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 31
step-start
{
  "type": "step-start",
  "id": "prt_1a1d75e9e001Pr3Xz6FPVP7RF2",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d75599001ZT4rYVMpVRpzkG"
}
Reasoning
Let me read the diff hunks for startup_config.py (323-386), README.md (983-1003), docker/README.md (1004-1116), cli_commands.py (1-185), common.py (186-216), features/base.py (217-235), features/credentials.py (236-300), features/pki.py (301-322), fos_cli_driver.py (387-448), fos_commander.py (449-860), launch.py (861-891), terminal.py (892-982), tests (1117-end).
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 1,
  "limit": 450
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py
2: index ea16d0f..1af3f4d 100644
3: --- a/fortinet/common/cli_commands.py
4: +++ b/fortinet/common/cli_commands.py
5: @@ -12,46 +12,72 @@ class SessionLossAction(Enum):
6:      CONTINUE = auto()
7:      VALIDATE = auto()
8:      FAIL = auto()
9:  
10:  
11: +class ContextLossAction(Enum):
12: +    RESTART_BLOCK = auto()
13: +    FAIL = auto()
14: +
15: +
16:  @dataclass(frozen=True, init=False)
17:  class CommandSpec:
18:      line: str
19:      completion_states: tuple = ()
20:      capture_output: bool = False
21:      suppress_output: bool = False
22:      session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK
23:      expected_completion_state: object = None
24:      fail_on_error: bool = False
25: +    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK
26: +    continuation: bool = False
27:  
28:      def __init__(self, line, completion_states=(), capture_output=False,
29:                   suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,
30: -                 expected_completion_state=None, fail_on_error=False):
31: +                 expected_completion_state=None, fail_on_error=False,
32: +                 context_loss=None, continuation=False):
33:          object.__setattr__(self, "line", line)
34:          object.__setattr__(self, "completion_states", completion_states)
35:          object.__setattr__(self, "capture_output", capture_output)
36:          object.__setattr__(self, "suppress_output", suppress_output)
37:          object.__setattr__(self, "session_loss", session_loss)
38:          object.__setattr__(self, "expected_completion_state", expected_completion_state)
39:          object.__setattr__(self, "fail_on_error", fail_on_error)
40: +        object.__setattr__(self, "continuation", continuation)
41: +        if context_loss is None:
42: +            # Commands that must not replay after logout must not replay after
43: +            # an unexpected scope exit either. Features can override this policy.
44: +            context_loss = (
45: +                ContextLossAction.RESTART_BLOCK
46: +                if session_loss == SessionLossAction.RESTART_BLOCK
47: +                else ContextLossAction.FAIL
48: +            )
49: +        object.__setattr__(self, "context_loss", context_loss)
50:          self.__post_init__()
51:  
52:      def __post_init__(self):
53:          if "\r" in self.line or "\n" in self.line:
54:              raise ValueError("CLI commands must contain exactly one line")
55:  
56: +    @property
57: +    def closes_scope(self):
58: +        return not self.continuation and self.line.strip().lower() in {"next", "end"}
59: +
60:  
61:  @dataclass
62:  class CommandAttempt:
63:      spec: CommandSpec
64:      number: int
65:      session_epoch: int
66:      output: bytearray = field(default_factory=bytearray)
67: +    prompt_context_before: tuple | None = None
68: +    prompt_context_after: tuple | None = None
69: +    block_index: int | None = None
70: +    retry_count: int = 0
71:  
72:      def on_output(self, output):
73: -        if not self.spec.capture_output:
74: +        if not (self.spec.capture_output or self.spec.closes_scope):
75:              return False
76:          data = bytes(output)
77:          self.output.extend(data)
78:          output.discard(data)
79:          return True
80: @@ -69,11 +95,11 @@ class Scope:
81:      @property
82:      def close_line(self):
83:          raise NotImplementedError
84:  
85:      def flatten(self):
86: -        commands = [CommandSpec(self.open_line)]
87: +        commands = flatten_commands(self.open_line)
88:          for child in self.children:
89:              commands.extend(flatten_commands(child))
90:          commands.append(CommandSpec(self.close_line))
91:          return commands
92:  
93: @@ -107,49 +133,43 @@ class SetValue:
94:          self.fail_on_error = fail_on_error
95:          self.validate_prompt = validate_prompt
96:  
97:      def flatten(self):
98:          lines = str(self.value).strip().splitlines() or [""]
99: -        if len(lines) == 1:
100: -            return [CommandSpec(
101: -                f'set {self.field} "{lines[0]}"',
102: -                capture_output=True,
103: -                expected_completion_state=(
104: -                    FOSCliState.CMD_PROMPT if self.validate_prompt else None
105: -                ),
106: -                fail_on_error=self.fail_on_error,
107: -            )]
108: -
109: -        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
110: -        commands = [CommandSpec(
111: -            f'set {self.field} "{lines[0]}',
112: -            completion_states=both_prompts,
113: -            capture_output=True,
114: -            expected_completion_state=(
115: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None
116: -            ),
117: -            fail_on_error=self.fail_on_error,
118: -        )]
119: -        commands.extend(CommandSpec(
120: -            line,
121: -            completion_states=both_prompts,
122: -            capture_output=True,
123: -            expected_completion_state=(
124: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None
125: -            ),
126: -            fail_on_error=self.fail_on_error,
127: -        ) for line in lines[1:-1])
128: +        lines[0] = f'set {self.field} "{lines[0]}'
129: +        lines[-1] += '"'
130: +        return _flatten_quoted_lines(
131: +            lines, fail_on_error=self.fail_on_error,
132: +            validate_prompt=self.validate_prompt,
133: +        )
134: +
135: +
136: +def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):
137: +    """Send a logical command one line per continuation prompt, without re-quoting."""
138: +    commands = []
139: +    for index, line in enumerate(lines):
140: +        last_line = index == len(lines) - 1
141: +        expected = (
142: +            FOSCliState.CMD_PROMPT if last_line
143: +            else FOSCliState.MULTILINE_PROMPT
144: +        )
145: +        completion_states = ()
146: +        if len(lines) > 1:
147: +            completion_states = (
148: +                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)
149: +                if last_line else
150: +                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)
151: +            )
152:          commands.append(CommandSpec(
153: -            f'{lines[-1]}"',
154: -            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),
155: +            line,
156: +            completion_states=completion_states,
157:              capture_output=True,
158: -            expected_completion_state=(
159: -                FOSCliState.CMD_PROMPT if self.validate_prompt else None
160: -            ),
161: -            fail_on_error=self.fail_on_error,
162: +            expected_completion_state=expected if validate_prompt else None,
163: +            fail_on_error=fail_on_error,
164: +            continuation=index > 0,
165:          ))
166: -        return commands
167: +    return commands
168:  
169:  
170:  class CommandSequence:
171:      """An unscoped workflow container; it does not emit CLI framing."""
172:  
173: @@ -165,10 +185,12 @@ class CommandSequence:
174:  
175:  
176:  def flatten_commands(value):
177:      """Flatten command containers and wrap plain CLI lines with defaults."""
178:      if isinstance(value, str):
179: +        if "\n" in value:
180: +            return _flatten_quoted_lines(value.split("\n"))
181:          return [CommandSpec(value)]
182:      if isinstance(value, CommandSpec):
183:          return [value]
184:      if isinstance(value, (Scope, CommandSequence, SetValue)):
185:          return value.flatten()
186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py
187: index 4ffb817..b020deb 100644
188: --- a/fortinet/common/common.py
189: +++ b/fortinet/common/common.py
190: @@ -21,10 +21,11 @@ class FOSCliState(IntEnum):
191:      CURRENT_PASSWORD = auto()
192:      CONFIRMATION = auto()
193:      CHANGE_PASSWORD_CONFIRM = auto()
194:      MORE_PROMPT = auto()
195:      MULTILINE_PROMPT = auto()
196: +    KERNEL_PANIC = auto()
197:      UNKNOWN = auto()  # Non-patterns from here on.
198:      TN_TIMEOUT = auto()
199:  
200:  
201:  GENERIC_HOSTNAME_REGEX = rb"[A-Za-z0-9_.-]+"
202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (
203:  )
204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb"(?mi)Do you want to continue\?"
205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb"(?mi)^Confirm Password:[ \t]*"
206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb"--More--\s*"
207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb"(?m)^>[ \t]*\r?$"
208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (
209: +    rb"(?mi)^Kernel panic(?: - not syncing)?:[^\r\n]*\r?\n"
210: +    rb"CPU: [0-9]+ PID: [0-9]+ Comm: [^\r\n]+"
211: +)
212:  
213:  DEF_POLICY_COMPLIANT_PASSWORD = "FortinetFOS1!"
214:  DEFAULT_USERNAME = "admin"
215:  DEFAULT_PASSWORD = DEFAULT_USERNAME
216:  
217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py
218: index 83ebc9b..5dd906a 100644
219: --- a/fortinet/common/features/base.py
220: +++ b/fortinet/common/features/base.py
221: @@ -53,10 +53,14 @@ class Feature:
222:          self.commander.feature_complete(self)
223:  
224:      def on_session_loss(self, attempt):
225:          return attempt.spec.session_loss
226:  
227: +    def on_context_loss(self, attempt):
228: +        """Choose whether the commander may replay this interrupted block."""
229: +        return attempt.spec.context_loss
230: +
231:      def reversal_blocks(self):
232:          """Return command blocks that completely reverse this feature's work."""
233:          return []
234:  
235:      def undo(self):
236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py
237: index b8bc7de..af39225 100644
238: --- a/fortinet/common/features/credentials.py
239: +++ b/fortinet/common/features/credentials.py
240: @@ -1,14 +1,15 @@
241:  """Administrator bootstrap feature."""
242:  
243: -from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction
244: +from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction
245: +from ..common import FOSCliState
246:  
247:  from .base import StaticFeature
248:  
249:  
250:  class CredentialsFeature(StaticFeature):
251: -    """Configure the administrator and change credentials after password loss."""
252: +    """Configure the administrator, then log out and authenticate again."""
253:  
254:      def __init__(self, vm, commander):
255:          self._activate_after_admin_commit = False
256:          self._desired_credentials_activated = False
257:          self._password_change_committed = False
258: @@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):
259:                  fail_on_error=True,
260:              ))
261:          super().__init__(vm, commander, "admin", [
262:              ConfigBlock("system password-policy", ["set status disable"]),
263:              ConfigBlock("system admin", [EditBlock(credentials.username, admin_children)]),
264: +            CommandSequence("admin-relogin", [CommandSpec(
265: +                "exit",
266: +                session_loss=SessionLossAction.CONTINUE,
267: +                capture_output=True,
268: +                fail_on_error=True,
269: +                # A successful logout takes the session-loss path. Returning
270: +                # straight to a CLI prompt must not count as verification.
271: +                expected_completion_state=FOSCliState.PROVIDE_USERNAME,
272: +            )]),
273:          ], on_complete=lambda: self._activate_desired_credentials())
274:  
275: +    def on_command_dispatched(self, attempt):
276: +        if attempt.spec.line == "exit":
277: +            self._activate_desired_credentials()
278: +        super().on_command_dispatched(attempt)
279: +
280:      def on_session_loss(self, attempt):
281: +        if attempt.spec.line == "exit":
282: +            # The commander resumes this block only at the authenticated CLI
283: +            # prompt. Clear the logout command so it cannot be replayed.
284: +            return SessionLossAction.CONTINUE
285:          if self._is_password_command(attempt.spec.line):
286:              self._activate_desired_credentials()
287:              self._activate_after_admin_commit = False
288:              return SessionLossAction.CONTINUE
289: +        if self._activate_after_admin_commit and attempt.spec.line == "next":
290: +            # Some releases log out during the commit instead of returning
291: +            # its CLI prompt. Authenticate with the committed password.
292: +            self._activate_desired_credentials()
293: +            self._activate_after_admin_commit = False
294: +            self._password_change_committed = True
295: +            return SessionLossAction.CONTINUE
296:          if self._password_change_committed:
297:              # FortiOS may log out as the admin edit closes. The password
298:              # command and `next` have already committed the new credentials,
299:              # so replaying this block would use the previous password again.
300:              return SessionLossAction.CONTINUE
301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py
302: index 96a90d3..a5f0de7 100644
303: --- a/fortinet/common/features/pki.py
304: +++ b/fortinet/common/features/pki.py
305: @@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):
306:      @staticmethod
307:      def _config_item_block(scope, name, children):
308:          # A configuration attempt is deliberately best-effort: the feature
309:          # must be able to inspect the result and fall back to the TFTP import
310:          # path when a firmware release does not expose this config tree.  If
311: -        # these wrapper commands keep ``fail_on_error`` enabled, the commander
312: -        # raises before ``on_command_executed`` can record the failed config
313: -        # attempt and select the fallback.
314: +        # opening commands keep ``fail_on_error`` enabled, the commander raises
315: +        # before ``on_command_executed`` can select that fallback. A return-code
316: +        # failure from `next` or `end` is always fatal to the feature: the
317: +        # commander checks scope commits even when fail_on_error is disabled.
318:          def config_command(line):
319:              return CommandSpec(line, capture_output=True, fail_on_error=False)
320:  
321:          return CommandSequence(f"{scope}-{name}", [
322:              config_command(f"config {scope}"),
323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py
324: index e404fc8..cb99aa4 100644
325: --- a/fortinet/common/features/startup_config.py
326: +++ b/fortinet/common/features/startup_config.py
327: @@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):
328:              "FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL"
329:          )
330:      return filtered
331:  
332:  
333: +def _startup_config_commands(config):
334: +    """Yield logical CLI commands while retaining quoted newlines verbatim."""
335: +    pending = []
336: +    quote = None
337: +    start_line = None
338: +    for number, raw_line in enumerate(config, start=1):
339: +        # Text mode normalizes file line endings. Only remove the delimiter;
340: +        # whitespace and comment/scope-looking lines inside quotes are data.
341: +        line = raw_line.removesuffix("\n")
342: +        if not pending:
343: +            line = line.lstrip()
344: +            if not line or line.startswith("#"):
345: +                continue
346: +            start_line = number
347: +
348: +        escaped = False
349: +        for character in line:
350: +            if escaped:
351: +                escaped = False
352: +            elif character == "\\":
353: +                escaped = True
354: +            elif character == quote:
355: +                quote = None
356: +            elif quote is None and character in {"'", '"'}:
357: +                quote = character
358: +
359: +        if quote is not None or escaped:
360: +            pending.append(line)
361: +            continue
362: +        pending.append(line.rstrip())
363: +        yield "\n".join(pending)
364: +        pending.clear()
365: +
366: +    if pending:
367: +        reason = "unterminated quoted string" if quote else "unfinished line continuation"
368: +        raise ValueError(
369: +            f"Startup config malformed. {reason} starting on line {start_line}."
370: +        )
371: +
372: +
373:  def parse_startup_config(path):
374:      roots = []
375:      stack = []
376:      with open(path) as config:
377: -        for raw_line in config:
378: -            line = raw_line.strip()
379: -            if not line or line.startswith("#"):
380: -                continue
381: +        for line in _startup_config_commands(config):
382:              if line.startswith("config "):
383:                  node = ConfigBlock(line[7:])
384:                  (stack[-1].children if stack else roots).append(node)
385:                  stack.append(node)
386:              elif line.startswith("edit "):
387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py
388: index fa34100..b527816 100644
389: --- a/fortinet/common/fos_cli_driver.py
390: +++ b/fortinet/common/fos_cli_driver.py
391: @@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10
392:  EXPECT_TIMEOUT_SECONDS = 1
393:  UNKNOWN_STALL_SECONDS = 30
394:  UNKNOWN_STALL_NEWLINE_LIMIT = 3
395:  
396:  
397: +class KernelPanicError(RuntimeError):
398: +    """Raised when the guest kernel reports a panic on the serial console."""
399: +
400: +
401:  class FOSCliDriver:
402:      """Owns serial reads and delegates command dispatch to the commander."""
403:  
404:      def __init__(
405:          self,
406: @@ -65,10 +69,11 @@ class FOSCliDriver:
407:              FOSCliState.CMD_PROMPT: self._command_prompt,
408:              FOSCliState.CMD_PROMPT_ECHO: None,
409:              FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,
410:              FOSCliState.LIC_FAIL: self._license_failed,
411:              FOSCliState.TN_TIMEOUT: self._timeout,
412: +            FOSCliState.KERNEL_PANIC: self._kernel_panic,
413:              FOSCliState.UNKNOWN: self._unknown,
414:          }
415:  
416:      @property
417:      def state_patterns(self):
418: @@ -145,11 +150,14 @@ class FOSCliDriver:
419:  
420:      def _next_state(self):
421:          index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)
422:          if match:
423:              return FOSCliState(index), output, True
424: -        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False
425: +        # A timeout exposes retained bytes too. Only fresh input should reset
426: +        # the unknown-output stall timer; an unchanged buffer is still idle.
427: +        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT
428: +        return state, output, False
429:  
430:      def _handle_state(self, state):
431:          handler = self._state_handlers.get(state)
432:          if handler:
433:              try:
434: @@ -254,10 +262,14 @@ class FOSCliDriver:
435:  
436:      def _unknown(self):
437:          if self._last_known_state == FOSCliState.REBOOTING:
438:              self._idle_spins += 1
439:  
440: +    @staticmethod
441: +    def _kernel_panic():
442: +        raise KernelPanicError("Kernel panic detected on serial console")
443: +
444:      def _note_unknown_output(self):
445:          self._unknown_started_at = time.monotonic()
446:  
447:      def _recover_unknown_stall(self):
448:          if self._unknown_started_at is None:
449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py
450: index 26312cf..86b1be6 100644

(Showing lines 1-450 of 2108. Use offset=451 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d761fa001MLq9E55DXoCqbQ",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d75599001ZT4rYVMpVRpzkG",
  "callID": "call_09a14f197cb9437aa136998e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 1,
      "limit": 450
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1: diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\n2: index ea16d0f..1af3f4d 100644\n3: --- a/fortinet/common/cli_commands.py\n4: +++ b/fortinet/common/cli_commands.py\n5: @@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n6:      CONTINUE = auto()\n7:      VALIDATE = auto()\n8:      FAIL = auto()\n9:  \n10:  \n11: +class ContextLossAction(Enum):\n12: +    RESTART_BLOCK = auto()\n13: +    FAIL = auto()\n14: +\n15: +\n16:  @dataclass(frozen=True, init=False)\n17:  class CommandSpec:\n18:      line: str\n19:      completion_states: tuple = ()\n20:      capture_output: bool = False\n21:      suppress_output: bool = False\n22:      session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n23:      expected_completion_state: object = None\n24:      fail_on_error: bool = False\n25: +    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n26: +    continuation: bool = False\n27:  \n28:      def __init__(self, line, completion_states=(), capture_output=False,\n29:                   suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n30: -                 expected_completion_state=None, fail_on_error=False):\n31: +                 expected_completion_state=None, fail_on_error=False,\n32: +                 context_loss=None, continuation=False):\n33:          object.__setattr__(self, \"line\", line)\n34:          object.__setattr__(self, \"completion_states\", completion_states)\n35:          object.__setattr__(self, \"capture_output\", capture_output)\n36:          object.__setattr__(self, \"suppress_output\", suppress_output)\n37:          object.__setattr__(self, \"session_loss\", session_loss)\n38:          object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n39:          object.__setattr__(self, \"fail_on_error\", fail_on_error)\n40: +        object.__setattr__(self, \"continuation\", continuation)\n41: +        if context_loss is None:\n42: +            # Commands that must not replay after logout must not replay after\n43: +            # an unexpected scope exit either. Features can override this policy.\n44: +            context_loss = (\n45: +                ContextLossAction.RESTART_BLOCK\n46: +                if session_loss == SessionLossAction.RESTART_BLOCK\n47: +                else ContextLossAction.FAIL\n48: +            )\n49: +        object.__setattr__(self, \"context_loss\", context_loss)\n50:          self.__post_init__()\n51:  \n52:      def __post_init__(self):\n53:          if \"\\r\" in self.line or \"\\n\" in self.line:\n54:              raise ValueError(\"CLI commands must contain exactly one line\")\n55:  \n56: +    @property\n57: +    def closes_scope(self):\n58: +        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n59: +\n60:  \n61:  @dataclass\n62:  class CommandAttempt:\n63:      spec: CommandSpec\n64:      number: int\n65:      session_epoch: int\n66:      output: bytearray = field(default_factory=bytearray)\n67: +    prompt_context_before: tuple | None = None\n68: +    prompt_context_after: tuple | None = None\n69: +    block_index: int | None = None\n70: +    retry_count: int = 0\n71:  \n72:      def on_output(self, output):\n73: -        if not self.spec.capture_output:\n74: +        if not (self.spec.capture_output or self.spec.closes_scope):\n75:              return False\n76:          data = bytes(output)\n77:          self.output.extend(data)\n78:          output.discard(data)\n79:          return True\n80: @@ -69,11 +95,11 @@ class Scope:\n81:      @property\n82:      def close_line(self):\n83:          raise NotImplementedError\n84:  \n85:      def flatten(self):\n86: -        commands = [CommandSpec(self.open_line)]\n87: +        commands = flatten_commands(self.open_line)\n88:          for child in self.children:\n89:              commands.extend(flatten_commands(child))\n90:          commands.append(CommandSpec(self.close_line))\n91:          return commands\n92:  \n93: @@ -107,49 +133,43 @@ class SetValue:\n94:          self.fail_on_error = fail_on_error\n95:          self.validate_prompt = validate_prompt\n96:  \n97:      def flatten(self):\n98:          lines = str(self.value).strip().splitlines() or [\"\"]\n99: -        if len(lines) == 1:\n100: -            return [CommandSpec(\n101: -                f'set {self.field} \"{lines[0]}\"',\n102: -                capture_output=True,\n103: -                expected_completion_state=(\n104: -                    FOSCliState.CMD_PROMPT if self.validate_prompt else None\n105: -                ),\n106: -                fail_on_error=self.fail_on_error,\n107: -            )]\n108: -\n109: -        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n110: -        commands = [CommandSpec(\n111: -            f'set {self.field} \"{lines[0]}',\n112: -            completion_states=both_prompts,\n113: -            capture_output=True,\n114: -            expected_completion_state=(\n115: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n116: -            ),\n117: -            fail_on_error=self.fail_on_error,\n118: -        )]\n119: -        commands.extend(CommandSpec(\n120: -            line,\n121: -            completion_states=both_prompts,\n122: -            capture_output=True,\n123: -            expected_completion_state=(\n124: -                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n125: -            ),\n126: -            fail_on_error=self.fail_on_error,\n127: -        ) for line in lines[1:-1])\n128: +        lines[0] = f'set {self.field} \"{lines[0]}'\n129: +        lines[-1] += '\"'\n130: +        return _flatten_quoted_lines(\n131: +            lines, fail_on_error=self.fail_on_error,\n132: +            validate_prompt=self.validate_prompt,\n133: +        )\n134: +\n135: +\n136: +def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n137: +    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n138: +    commands = []\n139: +    for index, line in enumerate(lines):\n140: +        last_line = index == len(lines) - 1\n141: +        expected = (\n142: +            FOSCliState.CMD_PROMPT if last_line\n143: +            else FOSCliState.MULTILINE_PROMPT\n144: +        )\n145: +        completion_states = ()\n146: +        if len(lines) > 1:\n147: +            completion_states = (\n148: +                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n149: +                if last_line else\n150: +                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n151: +            )\n152:          commands.append(CommandSpec(\n153: -            f'{lines[-1]}\"',\n154: -            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),\n155: +            line,\n156: +            completion_states=completion_states,\n157:              capture_output=True,\n158: -            expected_completion_state=(\n159: -                FOSCliState.CMD_PROMPT if self.validate_prompt else None\n160: -            ),\n161: -            fail_on_error=self.fail_on_error,\n162: +            expected_completion_state=expected if validate_prompt else None,\n163: +            fail_on_error=fail_on_error,\n164: +            continuation=index > 0,\n165:          ))\n166: -        return commands\n167: +    return commands\n168:  \n169:  \n170:  class CommandSequence:\n171:      \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n172:  \n173: @@ -165,10 +185,12 @@ class CommandSequence:\n174:  \n175:  \n176:  def flatten_commands(value):\n177:      \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n178:      if isinstance(value, str):\n179: +        if \"\\n\" in value:\n180: +            return _flatten_quoted_lines(value.split(\"\\n\"))\n181:          return [CommandSpec(value)]\n182:      if isinstance(value, CommandSpec):\n183:          return [value]\n184:      if isinstance(value, (Scope, CommandSequence, SetValue)):\n185:          return value.flatten()\n186: diff --git a/fortinet/common/common.py b/fortinet/common/common.py\n187: index 4ffb817..b020deb 100644\n188: --- a/fortinet/common/common.py\n189: +++ b/fortinet/common/common.py\n190: @@ -21,10 +21,11 @@ class FOSCliState(IntEnum):\n191:      CURRENT_PASSWORD = auto()\n192:      CONFIRMATION = auto()\n193:      CHANGE_PASSWORD_CONFIRM = auto()\n194:      MORE_PROMPT = auto()\n195:      MULTILINE_PROMPT = auto()\n196: +    KERNEL_PANIC = auto()\n197:      UNKNOWN = auto()  # Non-patterns from here on.\n198:      TN_TIMEOUT = auto()\n199:  \n200:  \n201:  GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n203:  )\n204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n209: +    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n210: +    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n211: +)\n212:  \n213:  DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n214:  DEFAULT_USERNAME = \"admin\"\n215:  DEFAULT_PASSWORD = DEFAULT_USERNAME\n216:  \n217: diff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\n218: index 83ebc9b..5dd906a 100644\n219: --- a/fortinet/common/features/base.py\n220: +++ b/fortinet/common/features/base.py\n221: @@ -53,10 +53,14 @@ class Feature:\n222:          self.commander.feature_complete(self)\n223:  \n224:      def on_session_loss(self, attempt):\n225:          return attempt.spec.session_loss\n226:  \n227: +    def on_context_loss(self, attempt):\n228: +        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n229: +        return attempt.spec.context_loss\n230: +\n231:      def reversal_blocks(self):\n232:          \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n233:          return []\n234:  \n235:      def undo(self):\n236: diff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\n237: index b8bc7de..af39225 100644\n238: --- a/fortinet/common/features/credentials.py\n239: +++ b/fortinet/common/features/credentials.py\n240: @@ -1,14 +1,15 @@\n241:  \"\"\"Administrator bootstrap feature.\"\"\"\n242:  \n243: -from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n244: +from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n245: +from ..common import FOSCliState\n246:  \n247:  from .base import StaticFeature\n248:  \n249:  \n250:  class CredentialsFeature(StaticFeature):\n251: -    \"\"\"Configure the administrator and change credentials after password loss.\"\"\"\n252: +    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n253:  \n254:      def __init__(self, vm, commander):\n255:          self._activate_after_admin_commit = False\n256:          self._desired_credentials_activated = False\n257:          self._password_change_committed = False\n258: @@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):\n259:                  fail_on_error=True,\n260:              ))\n261:          super().__init__(vm, commander, \"admin\", [\n262:              ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n263:              ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n264: +            CommandSequence(\"admin-relogin\", [CommandSpec(\n265: +                \"exit\",\n266: +                session_loss=SessionLossAction.CONTINUE,\n267: +                capture_output=True,\n268: +                fail_on_error=True,\n269: +                # A successful logout takes the session-loss path. Returning\n270: +                # straight to a CLI prompt must not count as verification.\n271: +                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n272: +            )]),\n273:          ], on_complete=lambda: self._activate_desired_credentials())\n274:  \n275: +    def on_command_dispatched(self, attempt):\n276: +        if attempt.spec.line == \"exit\":\n277: +            self._activate_desired_credentials()\n278: +        super().on_command_dispatched(attempt)\n279: +\n280:      def on_session_loss(self, attempt):\n281: +        if attempt.spec.line == \"exit\":\n282: +            # The commander resumes this block only at the authenticated CLI\n283: +            # prompt. Clear the logout command so it cannot be replayed.\n284: +            return SessionLossAction.CONTINUE\n285:          if self._is_password_command(attempt.spec.line):\n286:              self._activate_desired_credentials()\n287:              self._activate_after_admin_commit = False\n288:              return SessionLossAction.CONTINUE\n289: +        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n290: +            # Some releases log out during the commit instead of returning\n291: +            # its CLI prompt. Authenticate with the committed password.\n292: +            self._activate_desired_credentials()\n293: +            self._activate_after_admin_commit = False\n294: +            self._password_change_committed = True\n295: +            return SessionLossAction.CONTINUE\n296:          if self._password_change_committed:\n297:              # FortiOS may log out as the admin edit closes. The password\n298:              # command and `next` have already committed the new credentials,\n299:              # so replaying this block would use the previous password again.\n300:              return SessionLossAction.CONTINUE\n301: diff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\n302: index 96a90d3..a5f0de7 100644\n303: --- a/fortinet/common/features/pki.py\n304: +++ b/fortinet/common/features/pki.py\n305: @@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):\n306:      @staticmethod\n307:      def _config_item_block(scope, name, children):\n308:          # A configuration attempt is deliberately best-effort: the feature\n309:          # must be able to inspect the result and fall back to the TFTP import\n310:          # path when a firmware release does not expose this config tree.  If\n311: -        # these wrapper commands keep ``fail_on_error`` enabled, the commander\n312: -        # raises before ``on_command_executed`` can record the failed config\n313: -        # attempt and select the fallback.\n314: +        # opening commands keep ``fail_on_error`` enabled, the commander raises\n315: +        # before ``on_command_executed`` can select that fallback. A return-code\n316: +        # failure from `next` or `end` is always fatal to the feature: the\n317: +        # commander checks scope commits even when fail_on_error is disabled.\n318:          def config_command(line):\n319:              return CommandSpec(line, capture_output=True, fail_on_error=False)\n320:  \n321:          return CommandSequence(f\"{scope}-{name}\", [\n322:              config_command(f\"config {scope}\"),\n323: diff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\n324: index e404fc8..cb99aa4 100644\n325: --- a/fortinet/common/features/startup_config.py\n326: +++ b/fortinet/common/features/startup_config.py\n327: @@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):\n328:              \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n329:          )\n330:      return filtered\n331:  \n332:  \n333: +def _startup_config_commands(config):\n334: +    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n335: +    pending = []\n336: +    quote = None\n337: +    start_line = None\n338: +    for number, raw_line in enumerate(config, start=1):\n339: +        # Text mode normalizes file line endings. Only remove the delimiter;\n340: +        # whitespace and comment/scope-looking lines inside quotes are data.\n341: +        line = raw_line.removesuffix(\"\\n\")\n342: +        if not pending:\n343: +            line = line.lstrip()\n344: +            if not line or line.startswith(\"#\"):\n345: +                continue\n346: +            start_line = number\n347: +\n348: +        escaped = False\n349: +        for character in line:\n350: +            if escaped:\n351: +                escaped = False\n352: +            elif character == \"\\\\\":\n353: +                escaped = True\n354: +            elif character == quote:\n355: +                quote = None\n356: +            elif quote is None and character in {\"'\", '\"'}:\n357: +                quote = character\n358: +\n359: +        if quote is not None or escaped:\n360: +            pending.append(line)\n361: +            continue\n362: +        pending.append(line.rstrip())\n363: +        yield \"\\n\".join(pending)\n364: +        pending.clear()\n365: +\n366: +    if pending:\n367: +        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n368: +        raise ValueError(\n369: +            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n370: +        )\n371: +\n372: +\n373:  def parse_startup_config(path):\n374:      roots = []\n375:      stack = []\n376:      with open(path) as config:\n377: -        for raw_line in config:\n378: -            line = raw_line.strip()\n379: -            if not line or line.startswith(\"#\"):\n380: -                continue\n381: +        for line in _startup_config_commands(config):\n382:              if line.startswith(\"config \"):\n383:                  node = ConfigBlock(line[7:])\n384:                  (stack[-1].children if stack else roots).append(node)\n385:                  stack.append(node)\n386:              elif line.startswith(\"edit \"):\n387: diff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\n388: index fa34100..b527816 100644\n389: --- a/fortinet/common/fos_cli_driver.py\n390: +++ b/fortinet/common/fos_cli_driver.py\n391: @@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10\n392:  EXPECT_TIMEOUT_SECONDS = 1\n393:  UNKNOWN_STALL_SECONDS = 30\n394:  UNKNOWN_STALL_NEWLINE_LIMIT = 3\n395:  \n396:  \n397: +class KernelPanicError(RuntimeError):\n398: +    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n399: +\n400: +\n401:  class FOSCliDriver:\n402:      \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n403:  \n404:      def __init__(\n405:          self,\n406: @@ -65,10 +69,11 @@ class FOSCliDriver:\n407:              FOSCliState.CMD_PROMPT: self._command_prompt,\n408:              FOSCliState.CMD_PROMPT_ECHO: None,\n409:              FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n410:              FOSCliState.LIC_FAIL: self._license_failed,\n411:              FOSCliState.TN_TIMEOUT: self._timeout,\n412: +            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n413:              FOSCliState.UNKNOWN: self._unknown,\n414:          }\n415:  \n416:      @property\n417:      def state_patterns(self):\n418: @@ -145,11 +150,14 @@ class FOSCliDriver:\n419:  \n420:      def _next_state(self):\n421:          index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n422:          if match:\n423:              return FOSCliState(index), output, True\n424: -        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False\n425: +        # A timeout exposes retained bytes too. Only fresh input should reset\n426: +        # the unknown-output stall timer; an unchanged buffer is still idle.\n427: +        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n428: +        return state, output, False\n429:  \n430:      def _handle_state(self, state):\n431:          handler = self._state_handlers.get(state)\n432:          if handler:\n433:              try:\n434: @@ -254,10 +262,14 @@ class FOSCliDriver:\n435:  \n436:      def _unknown(self):\n437:          if self._last_known_state == FOSCliState.REBOOTING:\n438:              self._idle_spins += 1\n439:  \n440: +    @staticmethod\n441: +    def _kernel_panic():\n442: +        raise KernelPanicError(\"Kernel panic detected on serial console\")\n443: +\n444:      def _note_unknown_output(self):\n445:          self._unknown_started_at = time.monotonic()\n446:  \n447:      def _recover_unknown_stall(self):\n448:          if self._unknown_started_at is None:\n449: diff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\n450: index 26312cf..86b1be6 100644\n\n(Showing lines 1-450 of 2108. Use offset=451 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\nindex ea16d0f..1af3f4d 100644\n--- a/fortinet/common/cli_commands.py\n+++ b/fortinet/common/cli_commands.py\n@@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n     CONTINUE = auto()\n     VALIDATE = auto()\n     FAIL = auto()\n \n \n+class ContextLossAction(Enum):\n+    RESTART_BLOCK = auto()\n+    FAIL = auto()\n+\n+\n @dataclass(frozen=True, init=False)\n class CommandSpec:\n     line: str\n     completion_states: tuple = ()\n     capture_output: bool = False",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/fortinet/common/cli_commands.py b/fortinet/common/cli_commands.py\nindex ea16d0f..1af3f4d 100644\n--- a/fortinet/common/cli_commands.py\n+++ b/fortinet/common/cli_commands.py\n@@ -12,46 +12,72 @@ class SessionLossAction(Enum):\n     CONTINUE = auto()\n     VALIDATE = auto()\n     FAIL = auto()\n \n \n+class ContextLossAction(Enum):\n+    RESTART_BLOCK = auto()\n+    FAIL = auto()\n+\n+\n @dataclass(frozen=True, init=False)\n class CommandSpec:\n     line: str\n     completion_states: tuple = ()\n     capture_output: bool = False\n     suppress_output: bool = False\n     session_loss: SessionLossAction = SessionLossAction.RESTART_BLOCK\n     expected_completion_state: object = None\n     fail_on_error: bool = False\n+    context_loss: ContextLossAction = ContextLossAction.RESTART_BLOCK\n+    continuation: bool = False\n \n     def __init__(self, line, completion_states=(), capture_output=False,\n                  suppress_output=False, session_loss=SessionLossAction.RESTART_BLOCK,\n-                 expected_completion_state=None, fail_on_error=False):\n+                 expected_completion_state=None, fail_on_error=False,\n+                 context_loss=None, continuation=False):\n         object.__setattr__(self, \"line\", line)\n         object.__setattr__(self, \"completion_states\", completion_states)\n         object.__setattr__(self, \"capture_output\", capture_output)\n         object.__setattr__(self, \"suppress_output\", suppress_output)\n         object.__setattr__(self, \"session_loss\", session_loss)\n         object.__setattr__(self, \"expected_completion_state\", expected_completion_state)\n         object.__setattr__(self, \"fail_on_error\", fail_on_error)\n+        object.__setattr__(self, \"continuation\", continuation)\n+        if context_loss is None:\n+            # Commands that must not replay after logout must not replay after\n+            # an unexpected scope exit either. Features can override this policy.\n+            context_loss = (\n+                ContextLossAction.RESTART_BLOCK\n+                if session_loss == SessionLossAction.RESTART_BLOCK\n+                else ContextLossAction.FAIL\n+            )\n+        object.__setattr__(self, \"context_loss\", context_loss)\n         self.__post_init__()\n \n     def __post_init__(self):\n         if \"\\r\" in self.line or \"\\n\" in self.line:\n             raise ValueError(\"CLI commands must contain exactly one line\")\n \n+    @property\n+    def closes_scope(self):\n+        return not self.continuation and self.line.strip().lower() in {\"next\", \"end\"}\n+\n \n @dataclass\n class CommandAttempt:\n     spec: CommandSpec\n     number: int\n     session_epoch: int\n     output: bytearray = field(default_factory=bytearray)\n+    prompt_context_before: tuple | None = None\n+    prompt_context_after: tuple | None = None\n+    block_index: int | None = None\n+    retry_count: int = 0\n \n     def on_output(self, output):\n-        if not self.spec.capture_output:\n+        if not (self.spec.capture_output or self.spec.closes_scope):\n             return False\n         data = bytes(output)\n         self.output.extend(data)\n         output.discard(data)\n         return True\n@@ -69,11 +95,11 @@ class Scope:\n     @property\n     def close_line(self):\n         raise NotImplementedError\n \n     def flatten(self):\n-        commands = [CommandSpec(self.open_line)]\n+        commands = flatten_commands(self.open_line)\n         for child in self.children:\n             commands.extend(flatten_commands(child))\n         commands.append(CommandSpec(self.close_line))\n         return commands\n \n@@ -107,49 +133,43 @@ class SetValue:\n         self.fail_on_error = fail_on_error\n         self.validate_prompt = validate_prompt\n \n     def flatten(self):\n         lines = str(self.value).strip().splitlines() or [\"\"]\n-        if len(lines) == 1:\n-            return [CommandSpec(\n-                f'set {self.field} \"{lines[0]}\"',\n-                capture_output=True,\n-                expected_completion_state=(\n-                    FOSCliState.CMD_PROMPT if self.validate_prompt else None\n-                ),\n-                fail_on_error=self.fail_on_error,\n-            )]\n-\n-        both_prompts = (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n-        commands = [CommandSpec(\n-            f'set {self.field} \"{lines[0]}',\n-            completion_states=both_prompts,\n-            capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n-        )]\n-        commands.extend(CommandSpec(\n-            line,\n-            completion_states=both_prompts,\n-            capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.MULTILINE_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n-        ) for line in lines[1:-1])\n+        lines[0] = f'set {self.field} \"{lines[0]}'\n+        lines[-1] += '\"'\n+        return _flatten_quoted_lines(\n+            lines, fail_on_error=self.fail_on_error,\n+            validate_prompt=self.validate_prompt,\n+        )\n+\n+\n+def _flatten_quoted_lines(lines, *, fail_on_error=False, validate_prompt=True):\n+    \"\"\"Send a logical command one line per continuation prompt, without re-quoting.\"\"\"\n+    commands = []\n+    for index, line in enumerate(lines):\n+        last_line = index == len(lines) - 1\n+        expected = (\n+            FOSCliState.CMD_PROMPT if last_line\n+            else FOSCliState.MULTILINE_PROMPT\n+        )\n+        completion_states = ()\n+        if len(lines) > 1:\n+            completion_states = (\n+                (FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT)\n+                if last_line else\n+                (FOSCliState.MULTILINE_PROMPT, FOSCliState.CMD_PROMPT)\n+            )\n         commands.append(CommandSpec(\n-            f'{lines[-1]}\"',\n-            completion_states=(FOSCliState.CMD_PROMPT, FOSCliState.MULTILINE_PROMPT),\n+            line,\n+            completion_states=completion_states,\n             capture_output=True,\n-            expected_completion_state=(\n-                FOSCliState.CMD_PROMPT if self.validate_prompt else None\n-            ),\n-            fail_on_error=self.fail_on_error,\n+            expected_completion_state=expected if validate_prompt else None,\n+            fail_on_error=fail_on_error,\n+            continuation=index > 0,\n         ))\n-        return commands\n+    return commands\n \n \n class CommandSequence:\n     \"\"\"An unscoped workflow container; it does not emit CLI framing.\"\"\"\n \n@@ -165,10 +185,12 @@ class CommandSequence:\n \n \n def flatten_commands(value):\n     \"\"\"Flatten command containers and wrap plain CLI lines with defaults.\"\"\"\n     if isinstance(value, str):\n+        if \"\\n\" in value:\n+            return _flatten_quoted_lines(value.split(\"\\n\"))\n         return [CommandSpec(value)]\n     if isinstance(value, CommandSpec):\n         return [value]\n     if isinstance(value, (Scope, CommandSequence, SetValue)):\n         return value.flatten()\ndiff --git a/fortinet/common/common.py b/fortinet/common/common.py\nindex 4ffb817..b020deb 100644\n--- a/fortinet/common/common.py\n+++ b/fortinet/common/common.py\n@@ -21,10 +21,11 @@ class FOSCliState(IntEnum):\n     CURRENT_PASSWORD = auto()\n     CONFIRMATION = auto()\n     CHANGE_PASSWORD_CONFIRM = auto()\n     MORE_PROMPT = auto()\n     MULTILINE_PROMPT = auto()\n+    KERNEL_PANIC = auto()\n     UNKNOWN = auto()  # Non-patterns from here on.\n     TN_TIMEOUT = auto()\n \n \n GENERIC_HOSTNAME_REGEX = rb\"[A-Za-z0-9_.-]+\"\n@@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n )\n FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n+FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n+    rb\"(?mi)^Kernel panic(?: - not syncing)?:[^\\r\\n]*\\r?\\n\"\n+    rb\"CPU: [0-9]+ PID: [0-9]+ Comm: [^\\r\\n]+\"\n+)\n \n DEF_POLICY_COMPLIANT_PASSWORD = \"FortinetFOS1!\"\n DEFAULT_USERNAME = \"admin\"\n DEFAULT_PASSWORD = DEFAULT_USERNAME\n \ndiff --git a/fortinet/common/features/base.py b/fortinet/common/features/base.py\nindex 83ebc9b..5dd906a 100644\n--- a/fortinet/common/features/base.py\n+++ b/fortinet/common/features/base.py\n@@ -53,10 +53,14 @@ class Feature:\n         self.commander.feature_complete(self)\n \n     def on_session_loss(self, attempt):\n         return attempt.spec.session_loss\n \n+    def on_context_loss(self, attempt):\n+        \"\"\"Choose whether the commander may replay this interrupted block.\"\"\"\n+        return attempt.spec.context_loss\n+\n     def reversal_blocks(self):\n         \"\"\"Return command blocks that completely reverse this feature's work.\"\"\"\n         return []\n \n     def undo(self):\ndiff --git a/fortinet/common/features/credentials.py b/fortinet/common/features/credentials.py\nindex b8bc7de..af39225 100644\n--- a/fortinet/common/features/credentials.py\n+++ b/fortinet/common/features/credentials.py\n@@ -1,14 +1,15 @@\n \"\"\"Administrator bootstrap feature.\"\"\"\n \n-from ..cli_commands import CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n+from ..cli_commands import CommandSequence, CommandSpec, ConfigBlock, EditBlock, SessionLossAction\n+from ..common import FOSCliState\n \n from .base import StaticFeature\n \n \n class CredentialsFeature(StaticFeature):\n-    \"\"\"Configure the administrator and change credentials after password loss.\"\"\"\n+    \"\"\"Configure the administrator, then log out and authenticate again.\"\"\"\n \n     def __init__(self, vm, commander):\n         self._activate_after_admin_commit = False\n         self._desired_credentials_activated = False\n         self._password_change_committed = False\n@@ -28,17 +29,42 @@ class CredentialsFeature(StaticFeature):\n                 fail_on_error=True,\n             ))\n         super().__init__(vm, commander, \"admin\", [\n             ConfigBlock(\"system password-policy\", [\"set status disable\"]),\n             ConfigBlock(\"system admin\", [EditBlock(credentials.username, admin_children)]),\n+            CommandSequence(\"admin-relogin\", [CommandSpec(\n+                \"exit\",\n+                session_loss=SessionLossAction.CONTINUE,\n+                capture_output=True,\n+                fail_on_error=True,\n+                # A successful logout takes the session-loss path. Returning\n+                # straight to a CLI prompt must not count as verification.\n+                expected_completion_state=FOSCliState.PROVIDE_USERNAME,\n+            )]),\n         ], on_complete=lambda: self._activate_desired_credentials())\n \n+    def on_command_dispatched(self, attempt):\n+        if attempt.spec.line == \"exit\":\n+            self._activate_desired_credentials()\n+        super().on_command_dispatched(attempt)\n+\n     def on_session_loss(self, attempt):\n+        if attempt.spec.line == \"exit\":\n+            # The commander resumes this block only at the authenticated CLI\n+            # prompt. Clear the logout command so it cannot be replayed.\n+            return SessionLossAction.CONTINUE\n         if self._is_password_command(attempt.spec.line):\n             self._activate_desired_credentials()\n             self._activate_after_admin_commit = False\n             return SessionLossAction.CONTINUE\n+        if self._activate_after_admin_commit and attempt.spec.line == \"next\":\n+            # Some releases log out during the commit instead of returning\n+            # its CLI prompt. Authenticate with the committed password.\n+            self._activate_desired_credentials()\n+            self._activate_after_admin_commit = False\n+            self._password_change_committed = True\n+            return SessionLossAction.CONTINUE\n         if self._password_change_committed:\n             # FortiOS may log out as the admin edit closes. The password\n             # command and `next` have already committed the new credentials,\n             # so replaying this block would use the previous password again.\n             return SessionLossAction.CONTINUE\ndiff --git a/fortinet/common/features/pki.py b/fortinet/common/features/pki.py\nindex 96a90d3..a5f0de7 100644\n--- a/fortinet/common/features/pki.py\n+++ b/fortinet/common/features/pki.py\n@@ -297,13 +297,14 @@ class InstallPkiCertificates(Feature):\n     @staticmethod\n     def _config_item_block(scope, name, children):\n         # A configuration attempt is deliberately best-effort: the feature\n         # must be able to inspect the result and fall back to the TFTP import\n         # path when a firmware release does not expose this config tree.  If\n-        # these wrapper commands keep ``fail_on_error`` enabled, the commander\n-        # raises before ``on_command_executed`` can record the failed config\n-        # attempt and select the fallback.\n+        # opening commands keep ``fail_on_error`` enabled, the commander raises\n+        # before ``on_command_executed`` can select that fallback. A return-code\n+        # failure from `next` or `end` is always fatal to the feature: the\n+        # commander checks scope commits even when fail_on_error is disabled.\n         def config_command(line):\n             return CommandSpec(line, capture_output=True, fail_on_error=False)\n \n         return CommandSequence(f\"{scope}-{name}\", [\n             config_command(f\"config {scope}\"),\ndiff --git a/fortinet/common/features/startup_config.py b/fortinet/common/features/startup_config.py\nindex e404fc8..cb99aa4 100644\n--- a/fortinet/common/features/startup_config.py\n+++ b/fortinet/common/features/startup_config.py\n@@ -43,18 +43,55 @@ def filter_startup_config_blocks(blocks, logger):\n             \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n         )\n     return filtered\n \n \n+def _startup_config_commands(config):\n+    \"\"\"Yield logical CLI commands while retaining quoted newlines verbatim.\"\"\"\n+    pending = []\n+    quote = None\n+    start_line = None\n+    for number, raw_line in enumerate(config, start=1):\n+        # Text mode normalizes file line endings. Only remove the delimiter;\n+        # whitespace and comment/scope-looking lines inside quotes are data.\n+        line = raw_line.removesuffix(\"\\n\")\n+        if not pending:\n+            line = line.lstrip()\n+            if not line or line.startswith(\"#\"):\n+                continue\n+            start_line = number\n+\n+        escaped = False\n+        for character in line:\n+            if escaped:\n+                escaped = False\n+            elif character == \"\\\\\":\n+                escaped = True\n+            elif character == quote:\n+                quote = None\n+            elif quote is None and character in {\"'\", '\"'}:\n+                quote = character\n+\n+        if quote is not None or escaped:\n+            pending.append(line)\n+            continue\n+        pending.append(line.rstrip())\n+        yield \"\\n\".join(pending)\n+        pending.clear()\n+\n+    if pending:\n+        reason = \"unterminated quoted string\" if quote else \"unfinished line continuation\"\n+        raise ValueError(\n+            f\"Startup config malformed. {reason} starting on line {start_line}.\"\n+        )\n+\n+\n def parse_startup_config(path):\n     roots = []\n     stack = []\n     with open(path) as config:\n-        for raw_line in config:\n-            line = raw_line.strip()\n-            if not line or line.startswith(\"#\"):\n-                continue\n+        for line in _startup_config_commands(config):\n             if line.startswith(\"config \"):\n                 node = ConfigBlock(line[7:])\n                 (stack[-1].children if stack else roots).append(node)\n                 stack.append(node)\n             elif line.startswith(\"edit \"):\ndiff --git a/fortinet/common/fos_cli_driver.py b/fortinet/common/fos_cli_driver.py\nindex fa34100..b527816 100644\n--- a/fortinet/common/fos_cli_driver.py\n+++ b/fortinet/common/fos_cli_driver.py\n@@ -14,10 +14,14 @@ PROCESS_SPIN_SECONDS = 10\n EXPECT_TIMEOUT_SECONDS = 1\n UNKNOWN_STALL_SECONDS = 30\n UNKNOWN_STALL_NEWLINE_LIMIT = 3\n \n \n+class KernelPanicError(RuntimeError):\n+    \"\"\"Raised when the guest kernel reports a panic on the serial console.\"\"\"\n+\n+\n class FOSCliDriver:\n     \"\"\"Owns serial reads and delegates command dispatch to the commander.\"\"\"\n \n     def __init__(\n         self,\n@@ -65,10 +69,11 @@ class FOSCliDriver:\n             FOSCliState.CMD_PROMPT: self._command_prompt,\n             FOSCliState.CMD_PROMPT_ECHO: None,\n             FOSCliState.CREDENTIAL_REJECTED: self._credential_rejected,\n             FOSCliState.LIC_FAIL: self._license_failed,\n             FOSCliState.TN_TIMEOUT: self._timeout,\n+            FOSCliState.KERNEL_PANIC: self._kernel_panic,\n             FOSCliState.UNKNOWN: self._unknown,\n         }\n \n     @property\n     def state_patterns(self):\n@@ -145,11 +150,14 @@ class FOSCliDriver:\n \n     def _next_state(self):\n         index, match, output = self._terminal.expect(self._state_patterns, EXPECT_TIMEOUT_SECONDS)\n         if match:\n             return FOSCliState(index), output, True\n-        return (FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN), output, False\n+        # A timeout exposes retained bytes too. Only fresh input should reset\n+        # the unknown-output stall timer; an unchanged buffer is still idle.\n+        state = FOSCliState.UNKNOWN if output.received_new_data else FOSCliState.TN_TIMEOUT\n+        return state, output, False\n \n     def _handle_state(self, state):\n         handler = self._state_handlers.get(state)\n         if handler:\n             try:\n@@ -254,10 +262,14 @@ class FOSCliDriver:\n \n     def _unknown(self):\n         if self._last_known_state == FOSCliState.REBOOTING:\n             self._idle_spins += 1\n \n+    @staticmethod\n+    def _kernel_panic():\n+        raise KernelPanicError(\"Kernel panic detected on serial console\")\n+\n     def _note_unknown_output(self):\n         self._unknown_started_at = time.monotonic()\n \n     def _recover_unknown_stall(self):\n         if self._unknown_started_at is None:\ndiff --git a/fortinet/common/fos_commander.py b/fortinet/common/fos_commander.py\nindex 26312cf..86b1be6 100644",
        "lineStart": 1,
        "lineEnd": 450,
        "totalLines": 2108,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716609561,
      "end": 1793716609575
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d7622a001IfzFDPh648r3fN",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d75599001ZT4rYVMpVRpzkG",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 67148,
    "input": 691,
    "output": 25,
    "reasoning": 128,
    "cache": {
      "read": 66304,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d75599001ZT4rYVMpVRpzkG",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716606361,
    "completed": 1793716609582
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 67148,
    "input": 691,
    "output": 25,
    "reasoning": 128,
    "cache": {
      "read": 66304,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 32
step-start
{
  "type": "step-start",
  "id": "prt_1a1d76a9c001aBqUpXHpPsxvIR",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d76235001CrQLUvGxhTJyPU"
}
Reasoning
Continue reading diff.txt from 451 to ~1116 (fos_commander, launch, terminal, READMEs).
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 670,
  "offset": 451
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
451: --- a/fortinet/common/fos_commander.py
452: +++ b/fortinet/common/fos_commander.py
453: @@ -10,24 +10,29 @@ from .cli_commands import (
454:      CleanupAction,
455:      CommandAttempt,
456:      CommandSequence,
457:      CommandSpec,
458:      ConfigBlock,
459: +    ContextLossAction,
460:      SessionLossAction,
461:      flatten_commands,
462:  )
463:  from .terminal import Data
464: -from .common import FOSCliState, TRACE_LEVEL
465: +from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL
466:  
467:  DISPATCHABLE_COMPLETION_STATES = {
468:      FOSCliState.CMD_PROMPT,
469:      FOSCliState.CONFIRMATION,
470:      FOSCliState.MULTILINE_PROMPT,
471:  }
472:  COMMAND_FAILURE_PATTERN = re.compile(
473:      rb"(?mi)^\s*Command fail\.\s*Return code\s+(-?\d+)"
474:  )
475: +CLI_PROMPT_CONTEXT_PATTERN = re.compile(
476: +    rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX
477: +    + rb"(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$"
478: +)
479:  
480:  
481:  @dataclass
482:  class _StandardOutputContext:
483:      feature: object
484: @@ -35,10 +40,11 @@ class _StandardOutputContext:
485:      phase: str = "inspect"
486:      restore: bool = False
487:  
488:  
489:  class FOSCommander:
490: +    MAX_COMMAND_RECOVERY_RETRIES = 1
491:      _CONSOLE_OUTPUT_PATTERN = re.compile(rb"(?mi)^\s*set output (more|standard)\s*\r?$")
492:      _CONSOLE_INSPECT_LINE = "show full-configuration system console"
493:      _CONSOLE_STANDARD_LINE = "set output standard"
494:  
495:      def __init__(self, terminal, logger, continue_on_error=False):
496: @@ -65,23 +71,37 @@ class FOSCommander:
497:          self._start_time = datetime.datetime.now()
498:          self._continue_on_error = continue_on_error
499:          self._pending_feature_error = None
500:          self._current_state = None
501:          self._callback_failed = False
502: +        self._prompt_context = None
503: +        self._block_prompt_context = None
504: +        self._recovery_retries = {}
505: +        self._cleanup_retries = {}
506: +        self._replay_context_target = None
507: +        self._context_reset_attempted = False
508: +        self._in_context_reset = False
509:  
510:      def _call_feature(self, callback, *args):
511:          """Run a feature callback and apply best-effort policy at this boundary."""
512:          try:
513:              return callback(*args)
514:          except Exception as error:
515: -            if not self._continue_on_error:
516: -                raise
517: -            self.logger.exception("Bootstrap feature callback failed")
518: -            self._pending_feature_error = error
519: -            self._callback_failed = True
520: +            self._handle_work_error(error, from_callback=True)
521:              return None
522:  
523: +    def _handle_work_error(self, error, *, from_callback=False):
524: +        """Apply the configured failure policy after feature/recovery decisions."""
525: +        if not self._continue_on_error:
526: +            raise error
527: +        if from_callback:
528: +            self.logger.exception("Bootstrap feature callback failed")
529: +        else:
530: +            self.logger.error("Bootstrap work failed: %s", error, exc_info=error)
531: +        self._pending_feature_error = error
532: +        self._callback_failed = True
533: +
534:      def _recover_feature_error(self, *, at_idle_prompt=False):
535:          error = self._pending_feature_error
536:          if error is None or (
537:              self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
538:          ):
539: @@ -143,10 +163,13 @@ class FOSCommander:
540:              self._inflight = None
541:              self._suppression.close()
542:              self._suppression = ExitStack()
543:  
544:          self._in_cleanup = False
545: +        self._replay_context_target = None
546: +        self._in_context_reset = False
547: +        self._cleanup_retries.clear()
548:          self._feature_errors.append((failed_name, str(error)))
549:          return failed_name
550:  
551:      def record_feature_error(self, name, error):
552:          """Record a recoverable bootstrap problem without stopping the queue."""
553: @@ -184,10 +207,14 @@ class FOSCommander:
554:          if self.busy:
555:              raise RuntimeError("Cannot replace an active command block")
556:          commands = tuple(flatten_commands(block))
557:          self._active_commands = commands
558:          self._pending = deque(commands)
559: +        self._block_prompt_context = self._prompt_context
560: +        self._recovery_retries = {}
561: +        self._replay_context_target = None
562: +        self._context_reset_attempted = False
563:  
564:      def feature_complete(self, feature):
565:          if feature is not self._active_feature:
566:              return
567:          if self.busy:
568: @@ -242,10 +269,18 @@ class FOSCommander:
569:  
570:      def on_state(self, state, output):
571:          """Called by the driver for every recognized serial state."""
572:          self._current_state = state
573:          self._callback_failed = False
574: +        if state == FOSCliState.CMD_PROMPT:
575: +            context = self._extract_prompt_context(output)
576: +            if context is not None:
577: +                self._prompt_context = context
578: +            # Some releases return directly to a usable prompt after login,
579: +            # without a Welcome banner. The prompt also ends session recovery.
580: +            self._authenticated_once = True
581: +            self._recovering = False
582:          if self._pending_feature_error is not None:
583:              if state == FOSCliState.CMD_PROMPT:
584:                  self._recover_feature_error()
585:              elif state == FOSCliState.SESSION_LOST:
586:                  self._session_epoch += 1
587: @@ -275,13 +310,10 @@ class FOSCommander:
588:              return
589:          if state == FOSCliState.CREDENTIAL_ACCEPTED:
590:              self._authenticated_once = True
591:              self._recovering = False
592:              return
593: -        if state == FOSCliState.CMD_PROMPT:
594: -            self._authenticated_once = True
595: -
596:          if self._inflight and state in (
597:              self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
598:          ):
599:              self._complete_inflight(state)
600:              return
601: @@ -345,28 +377,41 @@ class FOSCommander:
602:          self._call_feature(self._active_feature.begin_activation)
603:          if self._pending_feature_error is None:
604:              self._call_feature(self._active_feature.activate)
605:  
606:      def _dispatch_next(self):
607: -        if self._inflight or self._recovering:
608: +        if self._inflight or self._recovering or self._pending_feature_error is not None:
609: +            return
610: +        if not self._restore_replay_context():
611:              return
612:          if not self._cleanup and self._active_feature is None:
613:              self._activate_next_feature()
614:              if self._active_feature is None:
615:                  return
616:          if self._cleanup:
617:              spec = self._cleanup.popleft()
618:              self._in_cleanup = True
619: +            block_index = None
620:          elif not self._pending:
621:              self._call_feature(self._active_feature.on_block_complete)
622:              return
623:          else:
624:              spec = self._pending.popleft()
625:              self._in_cleanup = False
626: +            block_index = len(self._active_commands) - len(self._pending) - 1
627: +        self._dispatch_command(spec, block_index)
628: +
629: +    def _dispatch_command(self, spec, block_index=None):
630:          self._attempt_number += 1
631:          self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)
632: -        if self._active_feature:
633: +        self._inflight.prompt_context_before = self._prompt_context
634: +        self._inflight.block_index = block_index
635: +        self._inflight.retry_count = (
636: +            self._cleanup_retries.get(id(spec), 0)
637: +            if self._in_cleanup else self._recovery_retries.get(block_index, 0)
638: +        )
639: +        if self._active_feature and not self._in_context_reset:
640:              self._call_feature(self._active_feature.on_command_dispatched, self._inflight)
641:              if self._pending_feature_error is not None:
642:                  return
643:          if spec.suppress_output:
644:              self._suppression.enter_context(self.terminal.suppress_output())
645: @@ -380,12 +425,34 @@ class FOSCommander:
646:      def _complete_inflight(self, state):
647:          attempt = self._inflight
648:          self._inflight = None
649:          self._suppression.close()
650:          self._suppression = ExitStack()
651: -        self._validate_completion(attempt, state)
652: +        attempt.prompt_context_after = self._prompt_context
653: +        if self._in_context_reset:
654: +            self._in_context_reset = False
655: +            self._dispatch_next()
656: +            return
657: +        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
658: +            self._handle_context_loss(attempt)
659: +            if self._pending_feature_error is not None:
660: +                self._recover_feature_error()
661: +            else:
662: +                self._dispatch_next()
663: +            return
664: +        try:
665: +            self._validate_completion(attempt, state)
666: +        except RuntimeError as error:
667: +            if state != FOSCliState.CMD_PROMPT:
668: +                # An interactive prompt cannot safely advance to another feature.
669: +                raise
670: +            self._handle_work_error(error)
671: +            if self._pending_feature_error is not None:
672: +                self._recover_feature_error()
673: +            return
674:          if self._in_cleanup:
675: +            self._cleanup_retries.pop(id(attempt.spec), None)
676:              self._in_cleanup = False
677:              self._dispatch_next()
678:              return
679:          if self._is_standard_output_command(attempt.spec):
680:              self._complete_standard_output_command(attempt)
681: @@ -404,24 +471,105 @@ class FOSCommander:
682:          if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:
683:              self._dispatch_next()
684:  
685:      @staticmethod
686:      def _validate_completion(attempt, state):
687: -        if attempt.spec.fail_on_error and (
688: +        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (
689:              failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))
690:          ):
691:              raise RuntimeError(
692: -                "FortiOS command failed "
693: +                f"FortiOS command {attempt.spec.line!r} failed "
694:                  f"(return code {failure.group(1).decode()})"
695:              )
696:          expected = attempt.spec.expected_completion_state
697:          if expected is not None and state != expected:
698:              raise RuntimeError(
699:                  "CLI command completed at unexpected prompt: "
700:                  f"expected {expected.name}, received {state.name}"
701:              )
702:  
703: +    def _prompt_context_changed(self, attempt):
704: +        before = attempt.prompt_context_before
705: +        after = attempt.prompt_context_after
706: +        return (
707: +            before is not None
708: +            and after is not None
709: +            and before != after
710: +            and not self._command_may_change_context(attempt.spec)
711: +        )
712: +
713: +    def _handle_context_loss(self, attempt):
714: +        reason = (
715: +            "CLI context changed from "
716: +            f"{self._format_prompt_context(attempt.prompt_context_before)} to "
717: +            f"{self._format_prompt_context(attempt.prompt_context_after)}"
718: +        )
719: +        if self._in_cleanup:
720: +            self._handle_work_error(RuntimeError(
721: +                f"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay"
722: +            ))
723: +            return
724: +        action = self._call_feature(self._active_feature.on_context_loss, attempt)
725: +        if self._pending_feature_error is not None:
726: +            return
727: +        if action == ContextLossAction.RESTART_BLOCK:
728: +            self._restart_active_block(attempt, reason)
729: +        elif action == ContextLossAction.FAIL:
730: +            self._handle_work_error(RuntimeError(
731: +                f"{reason} during {attempt.spec.line!r}; feature declined replay"
732: +            ))
733: +        else:
734: +            self._handle_work_error(ValueError(f"Unsupported context-loss action: {action!r}"))
735: +
736: +    def _restore_replay_context(self):
737: +        """Unwind a surviving partial scope once before replaying its openers."""
738: +        target = self._replay_context_target
739: +        if target is None:
740: +            return True
741: +        if self._prompt_context == target:
742: +            self._replay_context_target = None
743: +            return True
744: +        if self._context_reset_attempted:
745: +            self._handle_work_error(RuntimeError(
746: +                "Unable to restore CLI context before replay: expected "
747: +                f"{self._format_prompt_context(target)}, received "
748: +                f"{self._format_prompt_context(self._prompt_context or ())}"
749: +            ))
750: +            if self._pending_feature_error is not None:
751: +                self._recover_feature_error()
752: +            return False
753: +        self._context_reset_attempted = True
754: +        self._in_context_reset = True
755: +        self._dispatch_command(CommandSpec("abort", suppress_output=True))
756: +        return False
757: +
758: +    @staticmethod
759: +    def _command_may_change_context(spec):
760: +        if spec.continuation:
761: +            return False
762: +        command = spec.line.strip().lower()
763: +        return (
764: +            command.startswith(("config ", "edit "))
765: +            or command in {"next", "end", "abort", "exit", "quit"}
766: +            or command == "set vdom-mode multi-vdom"
767: +        )
768: +
769: +    @staticmethod
770: +    def _extract_prompt_context(output):
771: +        data = bytes(output)
772: +        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))
773: +        if not matches:
774: +            return None
775: +        return tuple(
776: +            item.decode(errors="replace")
777: +            for item in re.findall(rb"\(([^)]*)\)", matches[-1].group("context"))
778: +        )
779: +
780: +    @staticmethod
781: +    def _format_prompt_context(context):
782: +        return " ".join(f"({item})" for item in context) or "<top-level>"
783: +
784:      def _is_standard_output_command(self, spec):
785:          context = self._standard_output_context
786:          return context is not None and (
787:              spec.line == self._CONSOLE_INSPECT_LINE
788:              or (context.phase == "set-standard" and not self._pending)
789: @@ -466,11 +614,24 @@ class FOSCommander:
790:              return
791:          attempt = self._inflight
792:          self._inflight = None
793:          self._suppression.close()
794:          self._suppression = ExitStack()
795: +        if self._in_context_reset:
796: +            # Login may itself restore the target scope. The pending replay
797: +            # stays bounded by the original command's recovery allowance.
798: +            self._in_context_reset = False
799: +            return
800:          if self._in_cleanup:
801: +            retries = self._cleanup_retries.get(id(attempt.spec), 0)
802: +            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
803: +                self._handle_work_error(RuntimeError(
804: +                    f"Session lost repeatedly during cleanup {attempt.spec.line!r}; "
805: +                    "retry limit reached"
806: +                ))
807: +                return
808: +            self._cleanup_retries[id(attempt.spec)] = retries + 1
809:              self._cleanup.appendleft(attempt.spec)
810:              self._in_cleanup = False
811:              return
812:          self._schedule_feature_cleanup(self._active_feature, "interruption")
813:          action = self._call_feature(
814: @@ -481,24 +642,39 @@ class FOSCommander:
815:              return
816:          self.logger.info(
817:              f"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}"
818:          )
819:          action_handlers = {
820: -            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),
821: +            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(
822: +                attempt, "session lost"
823: +            ),
824:              SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),
825:              SessionLossAction.CONTINUE: lambda: self._pending.clear(),
826: -            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),
827: +            SessionLossAction.FAIL: lambda: self._handle_work_error(
828: +                RuntimeError(f"Session lost during {attempt.spec.line!r}")
829: +            ),
830:              SessionLossAction.VALIDATE: lambda: self._pending.clear(),
831:          }
832:          action_handlers[action]()
833:  
834: -    def _restart_active_block(self):
835: +    def _restart_active_block(self, attempt, reason):
836: +        retries = self._recovery_retries.get(attempt.block_index, 0)
837: +        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
838: +            self._handle_work_error(RuntimeError(
839: +                f"{reason} repeatedly during {attempt.spec.line!r}; "
840: +                f"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})"
841: +            ))
842: +            return
843: +        self._recovery_retries[attempt.block_index] = retries + 1
844:          self._pending = deque(self._active_commands)
845: -
846: -    @staticmethod
847: -    def _raise_session_loss(attempt):
848: -        raise RuntimeError(f"Session lost during {attempt.spec.line!r}")
849: +        self._replay_context_target = self._block_prompt_context
850: +        self._context_reset_attempted = False
851: +        self.logger.warning(
852: +            "%s during %s/%r; replaying block (command recovery %d/%d)",
853: +            reason, self._active_feature.name, attempt.spec.line,
854: +            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,
855: +        )
856:  
857:      def enqueue_runtime_feature(self, feature):
858:          return self.enqueue_runtime_features([feature])
859:  
860:      def enqueue_runtime_features(self, features):
861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py
862: index 4c2d808..3c112e1 100755
863: --- a/fortinet/common/launch.py
864: +++ b/fortinet/common/launch.py
865: @@ -30,11 +30,11 @@ from .features import (
866:      InstallPkiCertificates,
867:      ApplyStartupConfig,
868:      ValidateProduct,
869:  )
870:  from .env import get_env
871: -from .fos_cli_driver import FOSCliDriver
872: +from .fos_cli_driver import FOSCliDriver, KernelPanicError
873:  from .fos_commander import FOSCommander
874:  from .host_forwarded_bridge import HostForwardedBridge
875:  from .net_mgmt_strategy import NetMgmtStrategy
876:  from .passthrough_redirect import PassthroughRedirect
877:  from .terminal import Terminal
878: @@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):
879:          """
880:          if self._bootstrap_error is not None:
881:              return False
882:          try:
883:              self.driver.process_state()
884: +        except KernelPanicError:
885: +            self.stop()
886: +            raise
887:          except Exception as error:
888:              if self._exit_on_bootstrap_error or self.commander.startup_complete:
889:                  self.stop()
890:                  raise
891:              failed_work = self.commander.continue_after_error(
892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py
893: index 368238c..d124474 100644
894: --- a/fortinet/common/terminal.py
895: +++ b/fortinet/common/terminal.py
896: @@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():
897:  
898:  
899:  class Data:
900:      """A byte view returned by Terminal.expect with authority to discard itself."""
901:  
902: -    def __init__(self, value, discard_callback=None):
903: +    def __init__(self, value, discard_callback=None, *, received_new_data=None):
904:          self.value = bytes(value)
905:          self._discard_callback = discard_callback
906:          self.discarded = False
907: +        self.received_new_data = (
908: +            bool(self.value) if received_new_data is None else received_new_data
909: +        )
910:  
911:      def __bytes__(self):
912:          return self.value
913:  
914:      def __bool__(self):
915: @@ -213,36 +216,46 @@ class Terminal:
916:      def expect(self, regex_list, timeout=None):
917:          """Read until a pattern matches, retaining unmatched data across calls.
918:  
919:          The match ending earliest in the buffered stream wins. Data through that
920:          match is returned and discarded; data after it remains buffered.
921: +        On timeout, the entire unmatched buffer is returned for inspection and
922: +        stays buffered unless the caller explicitly discards it.
923:          """
924:          self._ensure_reader()
925:          deadline = None if timeout is None else time.monotonic() + timeout
926: -        received = bytearray()
927: +        received_new_data = False
928:          result = self._match(regex_list)
929:  
930:          while result is None:
931:              remaining = None if deadline is None else deadline - time.monotonic()
932:              if remaining is not None and remaining <= 0:
933: -                return -1, None, Data(bytes(received), self._discard_prefix)
934: +                return -1, None, Data(
935: +                    self._buffer,
936: +                    self._discard_prefix,
937: +                    received_new_data=received_new_data,
938: +                )
939:  
940:              data = self._read_queue.get(remaining)
941:              if data:
942:                  self._buffer.extend(data)
943:                  self._enforce_buffer_limit()
944: -                received.extend(data)
945: +                received_new_data = True
946:                  if (
947:                      get_env(RAW_SERIAL_LOG_ENV, "").lower() in ("1", "true", "yes")
948:                      and self._output_suppression_depth == 0
949:                  ):
950: -                    self._logger.log(TRACE_LEVEL - 1, f"buffer: {self._buffer}")
951: +                    self._logger.log(TRACE_LEVEL, f"buffer: {self._buffer}")
952:                  result = self._match(regex_list)
953:                  continue
954:  
955:              if deadline is not None and time.monotonic() >= deadline:
956: -                return -1, None, Data(bytes(received), self._discard_prefix)
957: +                return -1, None, Data(
958: +                    self._buffer,
959: +                    self._discard_prefix,
960: +                    received_new_data=received_new_data,
961: +                )
962:  
963:          index, match = result
964:          consumed = bytes(self._buffer[:match.end()])
965:          stable_match = re.search(regex_list[index], consumed)
966:          del self._buffer[:match.end()]
967: @@ -251,11 +264,14 @@ class Terminal:
968:      def _discard_prefix(self, data):
969:          """Discard bytes that a caller has consumed from the retained buffer."""
970:          if not data:
971:              return
972:          if not self._buffer.startswith(data):
973: -            self._logger.debug("Refusing to discard non-prefix terminal output")
974: +            message = "Refusing to discard non-prefix terminal output"
975: +            if self._logger.isEnabledFor(TRACE_LEVEL):
976: +                message += f": data={data!r}; buffer={self._buffer!r}"
977: +            self._logger.warning(message)
978:              return
979:          del self._buffer[:len(data)]
980:  
981:      def _enforce_buffer_limit(self):
982:          if len(self._buffer) <= self._buffer_limit:
983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md
984: index 1d95aea..37c576e 100644
985: --- a/fortinet/fortigate/README.md
986: +++ b/fortinet/fortigate/README.md
987: @@ -167,11 +167,15 @@ config system global
988:      set alias "lab-fgt"
989:  end
990:  ```
991:  
992:  The importer validates basic `config` / `edit` / `next` / `end` nesting and
993: -fails startup on malformed structure.
994: +fails startup on malformed structure or unterminated quoted strings. Single-
995: +and double-quoted values can span lines. Newlines, whitespace, blank lines,
996: +and scope keywords inside a quoted value are preserved. Each continued line
997: +is sent only after the CLI's continuation prompt; the closing line must return
998: +to a command prompt. An unexpected prompt follows the bootstrap error policy.
999:  
1000:  The bootstrap DNS servers selected from the container resolver or
1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config
1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS
1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup
1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md
1005: index 9e11b86..74a118d 100644
1006: --- a/fortinet/fortigate/docker/README.md
1007: +++ b/fortinet/fortigate/docker/README.md
1008: @@ -35,12 +35,15 @@ Important behavior:
1009:  - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of
1010:    writing to the serial connection directly. The writer preserves write order
1011:    and sends one queued chunk at a time, so commander/driver state handling is
1012:    not paced by each scrapli write call.
1013:  - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte
1014: -  view of what was just read or matched, and timeout `Data` can discard bytes
1015: -  from the terminal's retained buffer.
1016: +  view of the matched prefix or, on timeout, the entire unmatched buffer.
1017: +  Inspecting timeout `Data` leaves those bytes buffered so later input can
1018: +  complete a partial token. Calling `discard()` explicitly consumes the view.
1019: +  `received_new_data` distinguishes fresh input from another inspection of the
1020: +  same retained bytes, so idle waits still advance the driver's stall timer.
1021:  - When multiple regexes match buffered output, the match that ends earliest
1022:    wins. This avoids later, broader prompt patterns swallowing earlier prompts.
1023:  - Matched bytes are consumed from the buffer; bytes after the match stay queued
1024:    for the next state parse.
1025:  - Timeout bytes are not consumed automatically. A command, feature, or commander
1026: @@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.
1027:  The dispatcher sends one command at a time and waits for an appropriate state
1028:  before continuing. By default, a command completes at the next command prompt.
1029:  Some commands override completion states, for example confirmation prompts or
1030:  reboot messages.
1031:  
1032: +Scope-closing commands (`next` and `end`) always capture their output and check
1033: +for `Command fail. Return code <number>`, including builds that append a period
1034: +after the code. A closing failure stops the feature before completion callbacks
1035: +or further commands, even when `fail_on_error=False`. It follows the bootstrap
1036: +error policy: abort normally, or skip the failed feature when
1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for
1038: +individual `set` commands, which can deliberately tolerate unsupported fields.
1039: +
1040:  Session loss is explicit. Each command carries a `SessionLossAction`:
1041:  
1042:  - `RESTART_BLOCK`: replay the current block from the start
1043:  - `COMPLETE_BLOCK`: treat the block as complete
1044:  - `CONTINUE`: do not replay the disruptive command
1045:  - `VALIDATE`: reserve for commands that need post-loss validation
1046: -- `FAIL`: raise immediately
1047: +- `FAIL`: report failure through the configured bootstrap error policy
1048:  
1049:  This matters because commands such as license restore and password updates can
1050:  drop the active admin session. Replaying them blindly can corrupt state or loop.
1051:  
1052: +Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.
1053: +The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,
1054: +commands that allow session-loss replay also allow context-loss replay; commands
1055: +with another session-loss policy decline context-loss replay unless explicitly
1056: +configured otherwise. Context loss does not invoke session-loss callbacks, since
1057: +those may commit credential or licensing transitions.
1058: +
1059: +The commander allows one recovery per command position within a submitted block,
1060: +shared between context loss and session loss. Recovery replays the block's scope
1061: +openers and commands. If necessary, the commander sends one `abort` to restore
1062: +the block's initial prompt context before replay. A repeated loss at the same
1063: +command or failure to restore that context follows the bootstrap error policy.
1064: +The allowance resets when the feature submits a new block. Cleanup commands also
1065: +have one session-loss retry. Attempts expose `retry_count` and the prompt context
1066: +before and after execution so features can make their recovery decision.
1067: +
1068:  The dispatcher also manages cleanup actions and standard-output contexts.
1069:  Features can request console output mode `standard` for machine-readable output;
1070:  the dispatcher detects the current console mode, changes it only when needed,
1071:  and restores `more` after the feature completes.
1072:  
1073: @@ -219,22 +246,23 @@ begin_activation()
1074:  on_command_dispatched(attempt)
1075:  on_output(output)
1076:  on_command_executed(command, state)
1077:  on_block_complete()
1078:  on_session_loss(attempt)
1079: +on_context_loss(attempt)
1080:  mark_completed()
1081:  ```
1082:  
1083:  Static command features subclass `StaticFeature`; they submit a fixed list of
1084:  blocks and complete after the last block. Dynamic features subclass `Feature`
1085:  and submit follow-up blocks based on command output or timer ticks.
1086:  
1087:  Current bootstrap stages are:
1088:  
1089:  - `disk-format`: formats additional disks after the first FortiGate log disk
1090: -- `admin`: disables password policy, creates/updates the desired admin, and
1091: -  handles session loss during password changes
1092: +- `admin`: disables password policy, creates/updates the desired admin, then
1093: +  logs out and waits for console authentication before later stages run
1094:  - `image-info`: reads `get system status` once and stores the parsed
1095:    platform, major, minor, patch, and build on `vm.fos_version` for later
1096:    features
1097:  - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against
1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint
1099: @@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept
1100:  a blank default password first. The driver keeps separate bootstrap and desired
1101:  credentials so it can answer prompts with the password that is valid at that
1102:  moment.
1103:  
1104:  The desired credentials are activated after the admin edit commits. Password
1105: -command output is checked for FortiOS command failures. After a password
1106: -change, the driver first tries the desired credentials. If FortiOS rejects
1107: +command output is checked for FortiOS command failures. After closing the admin
1108: +configuration, the feature sends `exit` and waits for a successful login and CLI
1109: +prompt before completing. A logout during the commit also activates the new
1110: +credentials without replaying the password change. The driver first tries the
1111: +desired credentials. If FortiOS rejects
1112:  them, it retries immediately with the previously accepted credentials, without
1113:  replacing the desired credentials used for later logins.
1114:  
1115:  ### Prompt patterns change during bootstrap
1116:  
1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py
1118: new file mode 100644
1119: index 0000000..7dc469b
1120: --- /dev/null

(Showing lines 451-1120 of 2108. Use offset=1121 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d76be7001GW3IQlimfBOyop",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d76235001CrQLUvGxhTJyPU",
  "callID": "call_9cccd44a24b5460d8e9ebf00",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 670,
      "offset": 451
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n451: --- a/fortinet/common/fos_commander.py\n452: +++ b/fortinet/common/fos_commander.py\n453: @@ -10,24 +10,29 @@ from .cli_commands import (\n454:      CleanupAction,\n455:      CommandAttempt,\n456:      CommandSequence,\n457:      CommandSpec,\n458:      ConfigBlock,\n459: +    ContextLossAction,\n460:      SessionLossAction,\n461:      flatten_commands,\n462:  )\n463:  from .terminal import Data\n464: -from .common import FOSCliState, TRACE_LEVEL\n465: +from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n466:  \n467:  DISPATCHABLE_COMPLETION_STATES = {\n468:      FOSCliState.CMD_PROMPT,\n469:      FOSCliState.CONFIRMATION,\n470:      FOSCliState.MULTILINE_PROMPT,\n471:  }\n472:  COMMAND_FAILURE_PATTERN = re.compile(\n473:      rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n474:  )\n475: +CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n476: +    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n477: +    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n478: +)\n479:  \n480:  \n481:  @dataclass\n482:  class _StandardOutputContext:\n483:      feature: object\n484: @@ -35,10 +40,11 @@ class _StandardOutputContext:\n485:      phase: str = \"inspect\"\n486:      restore: bool = False\n487:  \n488:  \n489:  class FOSCommander:\n490: +    MAX_COMMAND_RECOVERY_RETRIES = 1\n491:      _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n492:      _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n493:      _CONSOLE_STANDARD_LINE = \"set output standard\"\n494:  \n495:      def __init__(self, terminal, logger, continue_on_error=False):\n496: @@ -65,23 +71,37 @@ class FOSCommander:\n497:          self._start_time = datetime.datetime.now()\n498:          self._continue_on_error = continue_on_error\n499:          self._pending_feature_error = None\n500:          self._current_state = None\n501:          self._callback_failed = False\n502: +        self._prompt_context = None\n503: +        self._block_prompt_context = None\n504: +        self._recovery_retries = {}\n505: +        self._cleanup_retries = {}\n506: +        self._replay_context_target = None\n507: +        self._context_reset_attempted = False\n508: +        self._in_context_reset = False\n509:  \n510:      def _call_feature(self, callback, *args):\n511:          \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n512:          try:\n513:              return callback(*args)\n514:          except Exception as error:\n515: -            if not self._continue_on_error:\n516: -                raise\n517: -            self.logger.exception(\"Bootstrap feature callback failed\")\n518: -            self._pending_feature_error = error\n519: -            self._callback_failed = True\n520: +            self._handle_work_error(error, from_callback=True)\n521:              return None\n522:  \n523: +    def _handle_work_error(self, error, *, from_callback=False):\n524: +        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n525: +        if not self._continue_on_error:\n526: +            raise error\n527: +        if from_callback:\n528: +            self.logger.exception(\"Bootstrap feature callback failed\")\n529: +        else:\n530: +            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n531: +        self._pending_feature_error = error\n532: +        self._callback_failed = True\n533: +\n534:      def _recover_feature_error(self, *, at_idle_prompt=False):\n535:          error = self._pending_feature_error\n536:          if error is None or (\n537:              self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n538:          ):\n539: @@ -143,10 +163,13 @@ class FOSCommander:\n540:              self._inflight = None\n541:              self._suppression.close()\n542:              self._suppression = ExitStack()\n543:  \n544:          self._in_cleanup = False\n545: +        self._replay_context_target = None\n546: +        self._in_context_reset = False\n547: +        self._cleanup_retries.clear()\n548:          self._feature_errors.append((failed_name, str(error)))\n549:          return failed_name\n550:  \n551:      def record_feature_error(self, name, error):\n552:          \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n553: @@ -184,10 +207,14 @@ class FOSCommander:\n554:          if self.busy:\n555:              raise RuntimeError(\"Cannot replace an active command block\")\n556:          commands = tuple(flatten_commands(block))\n557:          self._active_commands = commands\n558:          self._pending = deque(commands)\n559: +        self._block_prompt_context = self._prompt_context\n560: +        self._recovery_retries = {}\n561: +        self._replay_context_target = None\n562: +        self._context_reset_attempted = False\n563:  \n564:      def feature_complete(self, feature):\n565:          if feature is not self._active_feature:\n566:              return\n567:          if self.busy:\n568: @@ -242,10 +269,18 @@ class FOSCommander:\n569:  \n570:      def on_state(self, state, output):\n571:          \"\"\"Called by the driver for every recognized serial state.\"\"\"\n572:          self._current_state = state\n573:          self._callback_failed = False\n574: +        if state == FOSCliState.CMD_PROMPT:\n575: +            context = self._extract_prompt_context(output)\n576: +            if context is not None:\n577: +                self._prompt_context = context\n578: +            # Some releases return directly to a usable prompt after login,\n579: +            # without a Welcome banner. The prompt also ends session recovery.\n580: +            self._authenticated_once = True\n581: +            self._recovering = False\n582:          if self._pending_feature_error is not None:\n583:              if state == FOSCliState.CMD_PROMPT:\n584:                  self._recover_feature_error()\n585:              elif state == FOSCliState.SESSION_LOST:\n586:                  self._session_epoch += 1\n587: @@ -275,13 +310,10 @@ class FOSCommander:\n588:              return\n589:          if state == FOSCliState.CREDENTIAL_ACCEPTED:\n590:              self._authenticated_once = True\n591:              self._recovering = False\n592:              return\n593: -        if state == FOSCliState.CMD_PROMPT:\n594: -            self._authenticated_once = True\n595: -\n596:          if self._inflight and state in (\n597:              self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n598:          ):\n599:              self._complete_inflight(state)\n600:              return\n601: @@ -345,28 +377,41 @@ class FOSCommander:\n602:          self._call_feature(self._active_feature.begin_activation)\n603:          if self._pending_feature_error is None:\n604:              self._call_feature(self._active_feature.activate)\n605:  \n606:      def _dispatch_next(self):\n607: -        if self._inflight or self._recovering:\n608: +        if self._inflight or self._recovering or self._pending_feature_error is not None:\n609: +            return\n610: +        if not self._restore_replay_context():\n611:              return\n612:          if not self._cleanup and self._active_feature is None:\n613:              self._activate_next_feature()\n614:              if self._active_feature is None:\n615:                  return\n616:          if self._cleanup:\n617:              spec = self._cleanup.popleft()\n618:              self._in_cleanup = True\n619: +            block_index = None\n620:          elif not self._pending:\n621:              self._call_feature(self._active_feature.on_block_complete)\n622:              return\n623:          else:\n624:              spec = self._pending.popleft()\n625:              self._in_cleanup = False\n626: +            block_index = len(self._active_commands) - len(self._pending) - 1\n627: +        self._dispatch_command(spec, block_index)\n628: +\n629: +    def _dispatch_command(self, spec, block_index=None):\n630:          self._attempt_number += 1\n631:          self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n632: -        if self._active_feature:\n633: +        self._inflight.prompt_context_before = self._prompt_context\n634: +        self._inflight.block_index = block_index\n635: +        self._inflight.retry_count = (\n636: +            self._cleanup_retries.get(id(spec), 0)\n637: +            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n638: +        )\n639: +        if self._active_feature and not self._in_context_reset:\n640:              self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n641:              if self._pending_feature_error is not None:\n642:                  return\n643:          if spec.suppress_output:\n644:              self._suppression.enter_context(self.terminal.suppress_output())\n645: @@ -380,12 +425,34 @@ class FOSCommander:\n646:      def _complete_inflight(self, state):\n647:          attempt = self._inflight\n648:          self._inflight = None\n649:          self._suppression.close()\n650:          self._suppression = ExitStack()\n651: -        self._validate_completion(attempt, state)\n652: +        attempt.prompt_context_after = self._prompt_context\n653: +        if self._in_context_reset:\n654: +            self._in_context_reset = False\n655: +            self._dispatch_next()\n656: +            return\n657: +        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n658: +            self._handle_context_loss(attempt)\n659: +            if self._pending_feature_error is not None:\n660: +                self._recover_feature_error()\n661: +            else:\n662: +                self._dispatch_next()\n663: +            return\n664: +        try:\n665: +            self._validate_completion(attempt, state)\n666: +        except RuntimeError as error:\n667: +            if state != FOSCliState.CMD_PROMPT:\n668: +                # An interactive prompt cannot safely advance to another feature.\n669: +                raise\n670: +            self._handle_work_error(error)\n671: +            if self._pending_feature_error is not None:\n672: +                self._recover_feature_error()\n673: +            return\n674:          if self._in_cleanup:\n675: +            self._cleanup_retries.pop(id(attempt.spec), None)\n676:              self._in_cleanup = False\n677:              self._dispatch_next()\n678:              return\n679:          if self._is_standard_output_command(attempt.spec):\n680:              self._complete_standard_output_command(attempt)\n681: @@ -404,24 +471,105 @@ class FOSCommander:\n682:          if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n683:              self._dispatch_next()\n684:  \n685:      @staticmethod\n686:      def _validate_completion(attempt, state):\n687: -        if attempt.spec.fail_on_error and (\n688: +        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n689:              failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n690:          ):\n691:              raise RuntimeError(\n692: -                \"FortiOS command failed \"\n693: +                f\"FortiOS command {attempt.spec.line!r} failed \"\n694:                  f\"(return code {failure.group(1).decode()})\"\n695:              )\n696:          expected = attempt.spec.expected_completion_state\n697:          if expected is not None and state != expected:\n698:              raise RuntimeError(\n699:                  \"CLI command completed at unexpected prompt: \"\n700:                  f\"expected {expected.name}, received {state.name}\"\n701:              )\n702:  \n703: +    def _prompt_context_changed(self, attempt):\n704: +        before = attempt.prompt_context_before\n705: +        after = attempt.prompt_context_after\n706: +        return (\n707: +            before is not None\n708: +            and after is not None\n709: +            and before != after\n710: +            and not self._command_may_change_context(attempt.spec)\n711: +        )\n712: +\n713: +    def _handle_context_loss(self, attempt):\n714: +        reason = (\n715: +            \"CLI context changed from \"\n716: +            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n717: +            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n718: +        )\n719: +        if self._in_cleanup:\n720: +            self._handle_work_error(RuntimeError(\n721: +                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n722: +            ))\n723: +            return\n724: +        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n725: +        if self._pending_feature_error is not None:\n726: +            return\n727: +        if action == ContextLossAction.RESTART_BLOCK:\n728: +            self._restart_active_block(attempt, reason)\n729: +        elif action == ContextLossAction.FAIL:\n730: +            self._handle_work_error(RuntimeError(\n731: +                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n732: +            ))\n733: +        else:\n734: +            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n735: +\n736: +    def _restore_replay_context(self):\n737: +        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n738: +        target = self._replay_context_target\n739: +        if target is None:\n740: +            return True\n741: +        if self._prompt_context == target:\n742: +            self._replay_context_target = None\n743: +            return True\n744: +        if self._context_reset_attempted:\n745: +            self._handle_work_error(RuntimeError(\n746: +                \"Unable to restore CLI context before replay: expected \"\n747: +                f\"{self._format_prompt_context(target)}, received \"\n748: +                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n749: +            ))\n750: +            if self._pending_feature_error is not None:\n751: +                self._recover_feature_error()\n752: +            return False\n753: +        self._context_reset_attempted = True\n754: +        self._in_context_reset = True\n755: +        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n756: +        return False\n757: +\n758: +    @staticmethod\n759: +    def _command_may_change_context(spec):\n760: +        if spec.continuation:\n761: +            return False\n762: +        command = spec.line.strip().lower()\n763: +        return (\n764: +            command.startswith((\"config \", \"edit \"))\n765: +            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n766: +            or command == \"set vdom-mode multi-vdom\"\n767: +        )\n768: +\n769: +    @staticmethod\n770: +    def _extract_prompt_context(output):\n771: +        data = bytes(output)\n772: +        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n773: +        if not matches:\n774: +            return None\n775: +        return tuple(\n776: +            item.decode(errors=\"replace\")\n777: +            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n778: +        )\n779: +\n780: +    @staticmethod\n781: +    def _format_prompt_context(context):\n782: +        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n783: +\n784:      def _is_standard_output_command(self, spec):\n785:          context = self._standard_output_context\n786:          return context is not None and (\n787:              spec.line == self._CONSOLE_INSPECT_LINE\n788:              or (context.phase == \"set-standard\" and not self._pending)\n789: @@ -466,11 +614,24 @@ class FOSCommander:\n790:              return\n791:          attempt = self._inflight\n792:          self._inflight = None\n793:          self._suppression.close()\n794:          self._suppression = ExitStack()\n795: +        if self._in_context_reset:\n796: +            # Login may itself restore the target scope. The pending replay\n797: +            # stays bounded by the original command's recovery allowance.\n798: +            self._in_context_reset = False\n799: +            return\n800:          if self._in_cleanup:\n801: +            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n802: +            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n803: +                self._handle_work_error(RuntimeError(\n804: +                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n805: +                    \"retry limit reached\"\n806: +                ))\n807: +                return\n808: +            self._cleanup_retries[id(attempt.spec)] = retries + 1\n809:              self._cleanup.appendleft(attempt.spec)\n810:              self._in_cleanup = False\n811:              return\n812:          self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n813:          action = self._call_feature(\n814: @@ -481,24 +642,39 @@ class FOSCommander:\n815:              return\n816:          self.logger.info(\n817:              f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n818:          )\n819:          action_handlers = {\n820: -            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),\n821: +            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n822: +                attempt, \"session lost\"\n823: +            ),\n824:              SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n825:              SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n826: -            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),\n827: +            SessionLossAction.FAIL: lambda: self._handle_work_error(\n828: +                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n829: +            ),\n830:              SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n831:          }\n832:          action_handlers[action]()\n833:  \n834: -    def _restart_active_block(self):\n835: +    def _restart_active_block(self, attempt, reason):\n836: +        retries = self._recovery_retries.get(attempt.block_index, 0)\n837: +        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n838: +            self._handle_work_error(RuntimeError(\n839: +                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n840: +                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n841: +            ))\n842: +            return\n843: +        self._recovery_retries[attempt.block_index] = retries + 1\n844:          self._pending = deque(self._active_commands)\n845: -\n846: -    @staticmethod\n847: -    def _raise_session_loss(attempt):\n848: -        raise RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n849: +        self._replay_context_target = self._block_prompt_context\n850: +        self._context_reset_attempted = False\n851: +        self.logger.warning(\n852: +            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n853: +            reason, self._active_feature.name, attempt.spec.line,\n854: +            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n855: +        )\n856:  \n857:      def enqueue_runtime_feature(self, feature):\n858:          return self.enqueue_runtime_features([feature])\n859:  \n860:      def enqueue_runtime_features(self, features):\n861: diff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\n862: index 4c2d808..3c112e1 100755\n863: --- a/fortinet/common/launch.py\n864: +++ b/fortinet/common/launch.py\n865: @@ -30,11 +30,11 @@ from .features import (\n866:      InstallPkiCertificates,\n867:      ApplyStartupConfig,\n868:      ValidateProduct,\n869:  )\n870:  from .env import get_env\n871: -from .fos_cli_driver import FOSCliDriver\n872: +from .fos_cli_driver import FOSCliDriver, KernelPanicError\n873:  from .fos_commander import FOSCommander\n874:  from .host_forwarded_bridge import HostForwardedBridge\n875:  from .net_mgmt_strategy import NetMgmtStrategy\n876:  from .passthrough_redirect import PassthroughRedirect\n877:  from .terminal import Terminal\n878: @@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):\n879:          \"\"\"\n880:          if self._bootstrap_error is not None:\n881:              return False\n882:          try:\n883:              self.driver.process_state()\n884: +        except KernelPanicError:\n885: +            self.stop()\n886: +            raise\n887:          except Exception as error:\n888:              if self._exit_on_bootstrap_error or self.commander.startup_complete:\n889:                  self.stop()\n890:                  raise\n891:              failed_work = self.commander.continue_after_error(\n892: diff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\n893: index 368238c..d124474 100644\n894: --- a/fortinet/common/terminal.py\n895: +++ b/fortinet/common/terminal.py\n896: @@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():\n897:  \n898:  \n899:  class Data:\n900:      \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n901:  \n902: -    def __init__(self, value, discard_callback=None):\n903: +    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n904:          self.value = bytes(value)\n905:          self._discard_callback = discard_callback\n906:          self.discarded = False\n907: +        self.received_new_data = (\n908: +            bool(self.value) if received_new_data is None else received_new_data\n909: +        )\n910:  \n911:      def __bytes__(self):\n912:          return self.value\n913:  \n914:      def __bool__(self):\n915: @@ -213,36 +216,46 @@ class Terminal:\n916:      def expect(self, regex_list, timeout=None):\n917:          \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n918:  \n919:          The match ending earliest in the buffered stream wins. Data through that\n920:          match is returned and discarded; data after it remains buffered.\n921: +        On timeout, the entire unmatched buffer is returned for inspection and\n922: +        stays buffered unless the caller explicitly discards it.\n923:          \"\"\"\n924:          self._ensure_reader()\n925:          deadline = None if timeout is None else time.monotonic() + timeout\n926: -        received = bytearray()\n927: +        received_new_data = False\n928:          result = self._match(regex_list)\n929:  \n930:          while result is None:\n931:              remaining = None if deadline is None else deadline - time.monotonic()\n932:              if remaining is not None and remaining <= 0:\n933: -                return -1, None, Data(bytes(received), self._discard_prefix)\n934: +                return -1, None, Data(\n935: +                    self._buffer,\n936: +                    self._discard_prefix,\n937: +                    received_new_data=received_new_data,\n938: +                )\n939:  \n940:              data = self._read_queue.get(remaining)\n941:              if data:\n942:                  self._buffer.extend(data)\n943:                  self._enforce_buffer_limit()\n944: -                received.extend(data)\n945: +                received_new_data = True\n946:                  if (\n947:                      get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n948:                      and self._output_suppression_depth == 0\n949:                  ):\n950: -                    self._logger.log(TRACE_LEVEL - 1, f\"buffer: {self._buffer}\")\n951: +                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n952:                  result = self._match(regex_list)\n953:                  continue\n954:  \n955:              if deadline is not None and time.monotonic() >= deadline:\n956: -                return -1, None, Data(bytes(received), self._discard_prefix)\n957: +                return -1, None, Data(\n958: +                    self._buffer,\n959: +                    self._discard_prefix,\n960: +                    received_new_data=received_new_data,\n961: +                )\n962:  \n963:          index, match = result\n964:          consumed = bytes(self._buffer[:match.end()])\n965:          stable_match = re.search(regex_list[index], consumed)\n966:          del self._buffer[:match.end()]\n967: @@ -251,11 +264,14 @@ class Terminal:\n968:      def _discard_prefix(self, data):\n969:          \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n970:          if not data:\n971:              return\n972:          if not self._buffer.startswith(data):\n973: -            self._logger.debug(\"Refusing to discard non-prefix terminal output\")\n974: +            message = \"Refusing to discard non-prefix terminal output\"\n975: +            if self._logger.isEnabledFor(TRACE_LEVEL):\n976: +                message += f\": data={data!r}; buffer={self._buffer!r}\"\n977: +            self._logger.warning(message)\n978:              return\n979:          del self._buffer[:len(data)]\n980:  \n981:      def _enforce_buffer_limit(self):\n982:          if len(self._buffer) <= self._buffer_limit:\n983: diff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\n984: index 1d95aea..37c576e 100644\n985: --- a/fortinet/fortigate/README.md\n986: +++ b/fortinet/fortigate/README.md\n987: @@ -167,11 +167,15 @@ config system global\n988:      set alias \"lab-fgt\"\n989:  end\n990:  ```\n991:  \n992:  The importer validates basic `config` / `edit` / `next` / `end` nesting and\n993: -fails startup on malformed structure.\n994: +fails startup on malformed structure or unterminated quoted strings. Single-\n995: +and double-quoted values can span lines. Newlines, whitespace, blank lines,\n996: +and scope keywords inside a quoted value are preserved. Each continued line\n997: +is sent only after the CLI's continuation prompt; the closing line must return\n998: +to a command prompt. An unexpected prompt follows the bootstrap error policy.\n999:  \n1000:  The bootstrap DNS servers selected from the container resolver or\n1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\n1004: diff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\n1005: index 9e11b86..74a118d 100644\n1006: --- a/fortinet/fortigate/docker/README.md\n1007: +++ b/fortinet/fortigate/docker/README.md\n1008: @@ -35,12 +35,15 @@ Important behavior:\n1009:  - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n1010:    writing to the serial connection directly. The writer preserves write order\n1011:    and sends one queued chunk at a time, so commander/driver state handling is\n1012:    not paced by each scrapli write call.\n1013:  - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n1014: -  view of what was just read or matched, and timeout `Data` can discard bytes\n1015: -  from the terminal's retained buffer.\n1016: +  view of the matched prefix or, on timeout, the entire unmatched buffer.\n1017: +  Inspecting timeout `Data` leaves those bytes buffered so later input can\n1018: +  complete a partial token. Calling `discard()` explicitly consumes the view.\n1019: +  `received_new_data` distinguishes fresh input from another inspection of the\n1020: +  same retained bytes, so idle waits still advance the driver's stall timer.\n1021:  - When multiple regexes match buffered output, the match that ends earliest\n1022:    wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n1023:  - Matched bytes are consumed from the buffer; bytes after the match stay queued\n1024:    for the next state parse.\n1025:  - Timeout bytes are not consumed automatically. A command, feature, or commander\n1026: @@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.\n1027:  The dispatcher sends one command at a time and waits for an appropriate state\n1028:  before continuing. By default, a command completes at the next command prompt.\n1029:  Some commands override completion states, for example confirmation prompts or\n1030:  reboot messages.\n1031:  \n1032: +Scope-closing commands (`next` and `end`) always capture their output and check\n1033: +for `Command fail. Return code <number>`, including builds that append a period\n1034: +after the code. A closing failure stops the feature before completion callbacks\n1035: +or further commands, even when `fail_on_error=False`. It follows the bootstrap\n1036: +error policy: abort normally, or skip the failed feature when\n1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n1038: +individual `set` commands, which can deliberately tolerate unsupported fields.\n1039: +\n1040:  Session loss is explicit. Each command carries a `SessionLossAction`:\n1041:  \n1042:  - `RESTART_BLOCK`: replay the current block from the start\n1043:  - `COMPLETE_BLOCK`: treat the block as complete\n1044:  - `CONTINUE`: do not replay the disruptive command\n1045:  - `VALIDATE`: reserve for commands that need post-loss validation\n1046: -- `FAIL`: raise immediately\n1047: +- `FAIL`: report failure through the configured bootstrap error policy\n1048:  \n1049:  This matters because commands such as license restore and password updates can\n1050:  drop the active admin session. Replaying them blindly can corrupt state or loop.\n1051:  \n1052: +Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n1053: +The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n1054: +commands that allow session-loss replay also allow context-loss replay; commands\n1055: +with another session-loss policy decline context-loss replay unless explicitly\n1056: +configured otherwise. Context loss does not invoke session-loss callbacks, since\n1057: +those may commit credential or licensing transitions.\n1058: +\n1059: +The commander allows one recovery per command position within a submitted block,\n1060: +shared between context loss and session loss. Recovery replays the block's scope\n1061: +openers and commands. If necessary, the commander sends one `abort` to restore\n1062: +the block's initial prompt context before replay. A repeated loss at the same\n1063: +command or failure to restore that context follows the bootstrap error policy.\n1064: +The allowance resets when the feature submits a new block. Cleanup commands also\n1065: +have one session-loss retry. Attempts expose `retry_count` and the prompt context\n1066: +before and after execution so features can make their recovery decision.\n1067: +\n1068:  The dispatcher also manages cleanup actions and standard-output contexts.\n1069:  Features can request console output mode `standard` for machine-readable output;\n1070:  the dispatcher detects the current console mode, changes it only when needed,\n1071:  and restores `more` after the feature completes.\n1072:  \n1073: @@ -219,22 +246,23 @@ begin_activation()\n1074:  on_command_dispatched(attempt)\n1075:  on_output(output)\n1076:  on_command_executed(command, state)\n1077:  on_block_complete()\n1078:  on_session_loss(attempt)\n1079: +on_context_loss(attempt)\n1080:  mark_completed()\n1081:  ```\n1082:  \n1083:  Static command features subclass `StaticFeature`; they submit a fixed list of\n1084:  blocks and complete after the last block. Dynamic features subclass `Feature`\n1085:  and submit follow-up blocks based on command output or timer ticks.\n1086:  \n1087:  Current bootstrap stages are:\n1088:  \n1089:  - `disk-format`: formats additional disks after the first FortiGate log disk\n1090: -- `admin`: disables password policy, creates/updates the desired admin, and\n1091: -  handles session loss during password changes\n1092: +- `admin`: disables password policy, creates/updates the desired admin, then\n1093: +  logs out and waits for console authentication before later stages run\n1094:  - `image-info`: reads `get system status` once and stores the parsed\n1095:    platform, major, minor, patch, and build on `vm.fos_version` for later\n1096:    features\n1097:  - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n1099: @@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept\n1100:  a blank default password first. The driver keeps separate bootstrap and desired\n1101:  credentials so it can answer prompts with the password that is valid at that\n1102:  moment.\n1103:  \n1104:  The desired credentials are activated after the admin edit commits. Password\n1105: -command output is checked for FortiOS command failures. After a password\n1106: -change, the driver first tries the desired credentials. If FortiOS rejects\n1107: +command output is checked for FortiOS command failures. After closing the admin\n1108: +configuration, the feature sends `exit` and waits for a successful login and CLI\n1109: +prompt before completing. A logout during the commit also activates the new\n1110: +credentials without replaying the password change. The driver first tries the\n1111: +desired credentials. If FortiOS rejects\n1112:  them, it retries immediately with the previously accepted credentials, without\n1113:  replacing the desired credentials used for later logins.\n1114:  \n1115:  ### Prompt patterns change during bootstrap\n1116:  \n1117: diff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\n1118: new file mode 100644\n1119: index 0000000..7dc469b\n1120: --- /dev/null\n\n(Showing lines 451-1120 of 2108. Use offset=1121 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "--- a/fortinet/common/fos_commander.py\n+++ b/fortinet/common/fos_commander.py\n@@ -10,24 +10,29 @@ from .cli_commands import (\n     CleanupAction,\n     CommandAttempt,\n     CommandSequence,\n     CommandSpec,\n     ConfigBlock,\n+    ContextLossAction,\n     SessionLossAction,\n     flatten_commands,\n )\n from .terminal import Data\n-from .common import FOSCliState, TRACE_LEVEL\n+from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n \n DISPATCHABLE_COMPLETION_STATES = {\n     FOSCliState.CMD_PROMPT,\n     FOSCliState.CONFIRMATION,\n     FOSCliState.MULTILINE_PROMPT,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "--- a/fortinet/common/fos_commander.py\n+++ b/fortinet/common/fos_commander.py\n@@ -10,24 +10,29 @@ from .cli_commands import (\n     CleanupAction,\n     CommandAttempt,\n     CommandSequence,\n     CommandSpec,\n     ConfigBlock,\n+    ContextLossAction,\n     SessionLossAction,\n     flatten_commands,\n )\n from .terminal import Data\n-from .common import FOSCliState, TRACE_LEVEL\n+from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n \n DISPATCHABLE_COMPLETION_STATES = {\n     FOSCliState.CMD_PROMPT,\n     FOSCliState.CONFIRMATION,\n     FOSCliState.MULTILINE_PROMPT,\n }\n COMMAND_FAILURE_PATTERN = re.compile(\n     rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n )\n+CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n+    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n+    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n+)\n \n \n @dataclass\n class _StandardOutputContext:\n     feature: object\n@@ -35,10 +40,11 @@ class _StandardOutputContext:\n     phase: str = \"inspect\"\n     restore: bool = False\n \n \n class FOSCommander:\n+    MAX_COMMAND_RECOVERY_RETRIES = 1\n     _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n     _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n     _CONSOLE_STANDARD_LINE = \"set output standard\"\n \n     def __init__(self, terminal, logger, continue_on_error=False):\n@@ -65,23 +71,37 @@ class FOSCommander:\n         self._start_time = datetime.datetime.now()\n         self._continue_on_error = continue_on_error\n         self._pending_feature_error = None\n         self._current_state = None\n         self._callback_failed = False\n+        self._prompt_context = None\n+        self._block_prompt_context = None\n+        self._recovery_retries = {}\n+        self._cleanup_retries = {}\n+        self._replay_context_target = None\n+        self._context_reset_attempted = False\n+        self._in_context_reset = False\n \n     def _call_feature(self, callback, *args):\n         \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n         try:\n             return callback(*args)\n         except Exception as error:\n-            if not self._continue_on_error:\n-                raise\n-            self.logger.exception(\"Bootstrap feature callback failed\")\n-            self._pending_feature_error = error\n-            self._callback_failed = True\n+            self._handle_work_error(error, from_callback=True)\n             return None\n \n+    def _handle_work_error(self, error, *, from_callback=False):\n+        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n+        if not self._continue_on_error:\n+            raise error\n+        if from_callback:\n+            self.logger.exception(\"Bootstrap feature callback failed\")\n+        else:\n+            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n+        self._pending_feature_error = error\n+        self._callback_failed = True\n+\n     def _recover_feature_error(self, *, at_idle_prompt=False):\n         error = self._pending_feature_error\n         if error is None or (\n             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n         ):\n@@ -143,10 +163,13 @@ class FOSCommander:\n             self._inflight = None\n             self._suppression.close()\n             self._suppression = ExitStack()\n \n         self._in_cleanup = False\n+        self._replay_context_target = None\n+        self._in_context_reset = False\n+        self._cleanup_retries.clear()\n         self._feature_errors.append((failed_name, str(error)))\n         return failed_name\n \n     def record_feature_error(self, name, error):\n         \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n@@ -184,10 +207,14 @@ class FOSCommander:\n         if self.busy:\n             raise RuntimeError(\"Cannot replace an active command block\")\n         commands = tuple(flatten_commands(block))\n         self._active_commands = commands\n         self._pending = deque(commands)\n+        self._block_prompt_context = self._prompt_context\n+        self._recovery_retries = {}\n+        self._replay_context_target = None\n+        self._context_reset_attempted = False\n \n     def feature_complete(self, feature):\n         if feature is not self._active_feature:\n             return\n         if self.busy:\n@@ -242,10 +269,18 @@ class FOSCommander:\n \n     def on_state(self, state, output):\n         \"\"\"Called by the driver for every recognized serial state.\"\"\"\n         self._current_state = state\n         self._callback_failed = False\n+        if state == FOSCliState.CMD_PROMPT:\n+            context = self._extract_prompt_context(output)\n+            if context is not None:\n+                self._prompt_context = context\n+            # Some releases return directly to a usable prompt after login,\n+            # without a Welcome banner. The prompt also ends session recovery.\n+            self._authenticated_once = True\n+            self._recovering = False\n         if self._pending_feature_error is not None:\n             if state == FOSCliState.CMD_PROMPT:\n                 self._recover_feature_error()\n             elif state == FOSCliState.SESSION_LOST:\n                 self._session_epoch += 1\n@@ -275,13 +310,10 @@ class FOSCommander:\n             return\n         if state == FOSCliState.CREDENTIAL_ACCEPTED:\n             self._authenticated_once = True\n             self._recovering = False\n             return\n-        if state == FOSCliState.CMD_PROMPT:\n-            self._authenticated_once = True\n-\n         if self._inflight and state in (\n             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n         ):\n             self._complete_inflight(state)\n             return\n@@ -345,28 +377,41 @@ class FOSCommander:\n         self._call_feature(self._active_feature.begin_activation)\n         if self._pending_feature_error is None:\n             self._call_feature(self._active_feature.activate)\n \n     def _dispatch_next(self):\n-        if self._inflight or self._recovering:\n+        if self._inflight or self._recovering or self._pending_feature_error is not None:\n+            return\n+        if not self._restore_replay_context():\n             return\n         if not self._cleanup and self._active_feature is None:\n             self._activate_next_feature()\n             if self._active_feature is None:\n                 return\n         if self._cleanup:\n             spec = self._cleanup.popleft()\n             self._in_cleanup = True\n+            block_index = None\n         elif not self._pending:\n             self._call_feature(self._active_feature.on_block_complete)\n             return\n         else:\n             spec = self._pending.popleft()\n             self._in_cleanup = False\n+            block_index = len(self._active_commands) - len(self._pending) - 1\n+        self._dispatch_command(spec, block_index)\n+\n+    def _dispatch_command(self, spec, block_index=None):\n         self._attempt_number += 1\n         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n-        if self._active_feature:\n+        self._inflight.prompt_context_before = self._prompt_context\n+        self._inflight.block_index = block_index\n+        self._inflight.retry_count = (\n+            self._cleanup_retries.get(id(spec), 0)\n+            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n+        )\n+        if self._active_feature and not self._in_context_reset:\n             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n             if self._pending_feature_error is not None:\n                 return\n         if spec.suppress_output:\n             self._suppression.enter_context(self.terminal.suppress_output())\n@@ -380,12 +425,34 @@ class FOSCommander:\n     def _complete_inflight(self, state):\n         attempt = self._inflight\n         self._inflight = None\n         self._suppression.close()\n         self._suppression = ExitStack()\n-        self._validate_completion(attempt, state)\n+        attempt.prompt_context_after = self._prompt_context\n+        if self._in_context_reset:\n+            self._in_context_reset = False\n+            self._dispatch_next()\n+            return\n+        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n+            self._handle_context_loss(attempt)\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            else:\n+                self._dispatch_next()\n+            return\n+        try:\n+            self._validate_completion(attempt, state)\n+        except RuntimeError as error:\n+            if state != FOSCliState.CMD_PROMPT:\n+                # An interactive prompt cannot safely advance to another feature.\n+                raise\n+            self._handle_work_error(error)\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            return\n         if self._in_cleanup:\n+            self._cleanup_retries.pop(id(attempt.spec), None)\n             self._in_cleanup = False\n             self._dispatch_next()\n             return\n         if self._is_standard_output_command(attempt.spec):\n             self._complete_standard_output_command(attempt)\n@@ -404,24 +471,105 @@ class FOSCommander:\n         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n             self._dispatch_next()\n \n     @staticmethod\n     def _validate_completion(attempt, state):\n-        if attempt.spec.fail_on_error and (\n+        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n         ):\n             raise RuntimeError(\n-                \"FortiOS command failed \"\n+                f\"FortiOS command {attempt.spec.line!r} failed \"\n                 f\"(return code {failure.group(1).decode()})\"\n             )\n         expected = attempt.spec.expected_completion_state\n         if expected is not None and state != expected:\n             raise RuntimeError(\n                 \"CLI command completed at unexpected prompt: \"\n                 f\"expected {expected.name}, received {state.name}\"\n             )\n \n+    def _prompt_context_changed(self, attempt):\n+        before = attempt.prompt_context_before\n+        after = attempt.prompt_context_after\n+        return (\n+            before is not None\n+            and after is not None\n+            and before != after\n+            and not self._command_may_change_context(attempt.spec)\n+        )\n+\n+    def _handle_context_loss(self, attempt):\n+        reason = (\n+            \"CLI context changed from \"\n+            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n+            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n+        )\n+        if self._in_cleanup:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n+            ))\n+            return\n+        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n+        if self._pending_feature_error is not None:\n+            return\n+        if action == ContextLossAction.RESTART_BLOCK:\n+            self._restart_active_block(attempt, reason)\n+        elif action == ContextLossAction.FAIL:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n+            ))\n+        else:\n+            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n+\n+    def _restore_replay_context(self):\n+        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n+        target = self._replay_context_target\n+        if target is None:\n+            return True\n+        if self._prompt_context == target:\n+            self._replay_context_target = None\n+            return True\n+        if self._context_reset_attempted:\n+            self._handle_work_error(RuntimeError(\n+                \"Unable to restore CLI context before replay: expected \"\n+                f\"{self._format_prompt_context(target)}, received \"\n+                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n+            ))\n+            if self._pending_feature_error is not None:\n+                self._recover_feature_error()\n+            return False\n+        self._context_reset_attempted = True\n+        self._in_context_reset = True\n+        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n+        return False\n+\n+    @staticmethod\n+    def _command_may_change_context(spec):\n+        if spec.continuation:\n+            return False\n+        command = spec.line.strip().lower()\n+        return (\n+            command.startswith((\"config \", \"edit \"))\n+            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n+            or command == \"set vdom-mode multi-vdom\"\n+        )\n+\n+    @staticmethod\n+    def _extract_prompt_context(output):\n+        data = bytes(output)\n+        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n+        if not matches:\n+            return None\n+        return tuple(\n+            item.decode(errors=\"replace\")\n+            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n+        )\n+\n+    @staticmethod\n+    def _format_prompt_context(context):\n+        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n+\n     def _is_standard_output_command(self, spec):\n         context = self._standard_output_context\n         return context is not None and (\n             spec.line == self._CONSOLE_INSPECT_LINE\n             or (context.phase == \"set-standard\" and not self._pending)\n@@ -466,11 +614,24 @@ class FOSCommander:\n             return\n         attempt = self._inflight\n         self._inflight = None\n         self._suppression.close()\n         self._suppression = ExitStack()\n+        if self._in_context_reset:\n+            # Login may itself restore the target scope. The pending replay\n+            # stays bounded by the original command's recovery allowance.\n+            self._in_context_reset = False\n+            return\n         if self._in_cleanup:\n+            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n+            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n+                self._handle_work_error(RuntimeError(\n+                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n+                    \"retry limit reached\"\n+                ))\n+                return\n+            self._cleanup_retries[id(attempt.spec)] = retries + 1\n             self._cleanup.appendleft(attempt.spec)\n             self._in_cleanup = False\n             return\n         self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n         action = self._call_feature(\n@@ -481,24 +642,39 @@ class FOSCommander:\n             return\n         self.logger.info(\n             f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n         )\n         action_handlers = {\n-            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(),\n+            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n+                attempt, \"session lost\"\n+            ),\n             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n             SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n-            SessionLossAction.FAIL: lambda: self._raise_session_loss(attempt),\n+            SessionLossAction.FAIL: lambda: self._handle_work_error(\n+                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n+            ),\n             SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n         }\n         action_handlers[action]()\n \n-    def _restart_active_block(self):\n+    def _restart_active_block(self, attempt, reason):\n+        retries = self._recovery_retries.get(attempt.block_index, 0)\n+        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n+            self._handle_work_error(RuntimeError(\n+                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n+                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n+            ))\n+            return\n+        self._recovery_retries[attempt.block_index] = retries + 1\n         self._pending = deque(self._active_commands)\n-\n-    @staticmethod\n-    def _raise_session_loss(attempt):\n-        raise RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n+        self._replay_context_target = self._block_prompt_context\n+        self._context_reset_attempted = False\n+        self.logger.warning(\n+            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n+            reason, self._active_feature.name, attempt.spec.line,\n+            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n+        )\n \n     def enqueue_runtime_feature(self, feature):\n         return self.enqueue_runtime_features([feature])\n \n     def enqueue_runtime_features(self, features):\ndiff --git a/fortinet/common/launch.py b/fortinet/common/launch.py\nindex 4c2d808..3c112e1 100755\n--- a/fortinet/common/launch.py\n+++ b/fortinet/common/launch.py\n@@ -30,11 +30,11 @@ from .features import (\n     InstallPkiCertificates,\n     ApplyStartupConfig,\n     ValidateProduct,\n )\n from .env import get_env\n-from .fos_cli_driver import FOSCliDriver\n+from .fos_cli_driver import FOSCliDriver, KernelPanicError\n from .fos_commander import FOSCommander\n from .host_forwarded_bridge import HostForwardedBridge\n from .net_mgmt_strategy import NetMgmtStrategy\n from .passthrough_redirect import PassthroughRedirect\n from .terminal import Terminal\n@@ -326,10 +326,13 @@ class FortiOS_vm(vrnetlab.VM):\n         \"\"\"\n         if self._bootstrap_error is not None:\n             return False\n         try:\n             self.driver.process_state()\n+        except KernelPanicError:\n+            self.stop()\n+            raise\n         except Exception as error:\n             if self._exit_on_bootstrap_error or self.commander.startup_complete:\n                 self.stop()\n                 raise\n             failed_work = self.commander.continue_after_error(\ndiff --git a/fortinet/common/terminal.py b/fortinet/common/terminal.py\nindex 368238c..d124474 100644\n--- a/fortinet/common/terminal.py\n+++ b/fortinet/common/terminal.py\n@@ -28,14 +28,17 @@ def terminal_buffer_limit_bytes():\n \n \n class Data:\n     \"\"\"A byte view returned by Terminal.expect with authority to discard itself.\"\"\"\n \n-    def __init__(self, value, discard_callback=None):\n+    def __init__(self, value, discard_callback=None, *, received_new_data=None):\n         self.value = bytes(value)\n         self._discard_callback = discard_callback\n         self.discarded = False\n+        self.received_new_data = (\n+            bool(self.value) if received_new_data is None else received_new_data\n+        )\n \n     def __bytes__(self):\n         return self.value\n \n     def __bool__(self):\n@@ -213,36 +216,46 @@ class Terminal:\n     def expect(self, regex_list, timeout=None):\n         \"\"\"Read until a pattern matches, retaining unmatched data across calls.\n \n         The match ending earliest in the buffered stream wins. Data through that\n         match is returned and discarded; data after it remains buffered.\n+        On timeout, the entire unmatched buffer is returned for inspection and\n+        stays buffered unless the caller explicitly discards it.\n         \"\"\"\n         self._ensure_reader()\n         deadline = None if timeout is None else time.monotonic() + timeout\n-        received = bytearray()\n+        received_new_data = False\n         result = self._match(regex_list)\n \n         while result is None:\n             remaining = None if deadline is None else deadline - time.monotonic()\n             if remaining is not None and remaining <= 0:\n-                return -1, None, Data(bytes(received), self._discard_prefix)\n+                return -1, None, Data(\n+                    self._buffer,\n+                    self._discard_prefix,\n+                    received_new_data=received_new_data,\n+                )\n \n             data = self._read_queue.get(remaining)\n             if data:\n                 self._buffer.extend(data)\n                 self._enforce_buffer_limit()\n-                received.extend(data)\n+                received_new_data = True\n                 if (\n                     get_env(RAW_SERIAL_LOG_ENV, \"\").lower() in (\"1\", \"true\", \"yes\")\n                     and self._output_suppression_depth == 0\n                 ):\n-                    self._logger.log(TRACE_LEVEL - 1, f\"buffer: {self._buffer}\")\n+                    self._logger.log(TRACE_LEVEL, f\"buffer: {self._buffer}\")\n                 result = self._match(regex_list)\n                 continue\n \n             if deadline is not None and time.monotonic() >= deadline:\n-                return -1, None, Data(bytes(received), self._discard_prefix)\n+                return -1, None, Data(\n+                    self._buffer,\n+                    self._discard_prefix,\n+                    received_new_data=received_new_data,\n+                )\n \n         index, match = result\n         consumed = bytes(self._buffer[:match.end()])\n         stable_match = re.search(regex_list[index], consumed)\n         del self._buffer[:match.end()]\n@@ -251,11 +264,14 @@ class Terminal:\n     def _discard_prefix(self, data):\n         \"\"\"Discard bytes that a caller has consumed from the retained buffer.\"\"\"\n         if not data:\n             return\n         if not self._buffer.startswith(data):\n-            self._logger.debug(\"Refusing to discard non-prefix terminal output\")\n+            message = \"Refusing to discard non-prefix terminal output\"\n+            if self._logger.isEnabledFor(TRACE_LEVEL):\n+                message += f\": data={data!r}; buffer={self._buffer!r}\"\n+            self._logger.warning(message)\n             return\n         del self._buffer[:len(data)]\n \n     def _enforce_buffer_limit(self):\n         if len(self._buffer) <= self._buffer_limit:\ndiff --git a/fortinet/fortigate/README.md b/fortinet/fortigate/README.md\nindex 1d95aea..37c576e 100644\n--- a/fortinet/fortigate/README.md\n+++ b/fortinet/fortigate/README.md\n@@ -167,11 +167,15 @@ config system global\n     set alias \"lab-fgt\"\n end\n ```\n \n The importer validates basic `config` / `edit` / `next` / `end` nesting and\n-fails startup on malformed structure.\n+fails startup on malformed structure or unterminated quoted strings. Single-\n+and double-quoted values can span lines. Newlines, whitespace, blank lines,\n+and scope keywords inside a quoted value are preserved. Each continued line\n+is sent only after the CLI's continuation prompt; the closing line must return\n+to a command prompt. An unexpected prompt follows the bootstrap error policy.\n \n The bootstrap DNS servers selected from the container resolver or\n `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\ndiff --git a/fortinet/fortigate/docker/README.md b/fortinet/fortigate/docker/README.md\nindex 9e11b86..74a118d 100644\n--- a/fortinet/fortigate/docker/README.md\n+++ b/fortinet/fortigate/docker/README.md\n@@ -35,12 +35,15 @@ Important behavior:\n - `Terminal.write()` queues bytes for a terminal-owned writer thread instead of\n   writing to the serial connection directly. The writer preserves write order\n   and sends one queued chunk at a time, so commander/driver state handling is\n   not paced by each scrapli write call.\n - `Terminal.expect()` returns a `Data` object, not raw bytes. `Data` is a byte\n-  view of what was just read or matched, and timeout `Data` can discard bytes\n-  from the terminal's retained buffer.\n+  view of the matched prefix or, on timeout, the entire unmatched buffer.\n+  Inspecting timeout `Data` leaves those bytes buffered so later input can\n+  complete a partial token. Calling `discard()` explicitly consumes the view.\n+  `received_new_data` distinguishes fresh input from another inspection of the\n+  same retained bytes, so idle waits still advance the driver's stall timer.\n - When multiple regexes match buffered output, the match that ends earliest\n   wins. This avoids later, broader prompt patterns swallowing earlier prompts.\n - Matched bytes are consumed from the buffer; bytes after the match stay queued\n   for the next state parse.\n - Timeout bytes are not consumed automatically. A command, feature, or commander\n@@ -126,21 +129,45 @@ identity, and feature state machines track phase when they need context.\n The dispatcher sends one command at a time and waits for an appropriate state\n before continuing. By default, a command completes at the next command prompt.\n Some commands override completion states, for example confirmation prompts or\n reboot messages.\n \n+Scope-closing commands (`next` and `end`) always capture their output and check\n+for `Command fail. Return code <number>`, including builds that append a period\n+after the code. A closing failure stops the feature before completion callbacks\n+or further commands, even when `fail_on_error=False`. It follows the bootstrap\n+error policy: abort normally, or skip the failed feature when\n+`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n+individual `set` commands, which can deliberately tolerate unsupported fields.\n+\n Session loss is explicit. Each command carries a `SessionLossAction`:\n \n - `RESTART_BLOCK`: replay the current block from the start\n - `COMPLETE_BLOCK`: treat the block as complete\n - `CONTINUE`: do not replay the disruptive command\n - `VALIDATE`: reserve for commands that need post-loss validation\n-- `FAIL`: raise immediately\n+- `FAIL`: report failure through the configured bootstrap error policy\n \n This matters because commands such as license restore and password updates can\n drop the active admin session. Replaying them blindly can corrupt state or loop.\n \n+Unexpected prompt context changes call `Feature.on_context_loss(attempt)`.\n+The feature returns `ContextLossAction.RESTART_BLOCK` or `FAIL`. By default,\n+commands that allow session-loss replay also allow context-loss replay; commands\n+with another session-loss policy decline context-loss replay unless explicitly\n+configured otherwise. Context loss does not invoke session-loss callbacks, since\n+those may commit credential or licensing transitions.\n+\n+The commander allows one recovery per command position within a submitted block,\n+shared between context loss and session loss. Recovery replays the block's scope\n+openers and commands. If necessary, the commander sends one `abort` to restore\n+the block's initial prompt context before replay. A repeated loss at the same\n+command or failure to restore that context follows the bootstrap error policy.\n+The allowance resets when the feature submits a new block. Cleanup commands also\n+have one session-loss retry. Attempts expose `retry_count` and the prompt context\n+before and after execution so features can make their recovery decision.\n+\n The dispatcher also manages cleanup actions and standard-output contexts.\n Features can request console output mode `standard` for machine-readable output;\n the dispatcher detects the current console mode, changes it only when needed,\n and restores `more` after the feature completes.\n \n@@ -219,22 +246,23 @@ begin_activation()\n on_command_dispatched(attempt)\n on_output(output)\n on_command_executed(command, state)\n on_block_complete()\n on_session_loss(attempt)\n+on_context_loss(attempt)\n mark_completed()\n ```\n \n Static command features subclass `StaticFeature`; they submit a fixed list of\n blocks and complete after the last block. Dynamic features subclass `Feature`\n and submit follow-up blocks based on command output or timer ticks.\n \n Current bootstrap stages are:\n \n - `disk-format`: formats additional disks after the first FortiGate log disk\n-- `admin`: disables password policy, creates/updates the desired admin, and\n-  handles session loss during password changes\n+- `admin`: disables password policy, creates/updates the desired admin, then\n+  logs out and waits for console authentication before later stages run\n - `image-info`: reads `get system status` once and stores the parsed\n   platform, major, minor, patch, and build on `vm.fos_version` for later\n   features\n - `product-validation`: validates `vm.fos_product` and `vm.fos_version` against\n   the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n@@ -308,12 +336,15 @@ password, some require first-login password changes, and some older paths accept\n a blank default password first. The driver keeps separate bootstrap and desired\n credentials so it can answer prompts with the password that is valid at that\n moment.\n \n The desired credentials are activated after the admin edit commits. Password\n-command output is checked for FortiOS command failures. After a password\n-change, the driver first tries the desired credentials. If FortiOS rejects\n+command output is checked for FortiOS command failures. After closing the admin\n+configuration, the feature sends `exit` and waits for a successful login and CLI\n+prompt before completing. A logout during the commit also activates the new\n+credentials without replaying the password change. The driver first tries the\n+desired credentials. If FortiOS rejects\n them, it retries immediately with the previously accepted credentials, without\n replacing the desired credentials used for later logins.\n \n ### Prompt patterns change during bootstrap\n \ndiff --git a/fortinet/tests/test_common_admin_credentials.py b/fortinet/tests/test_common_admin_credentials.py\nnew file mode 100644\nindex 0000000..7dc469b\n--- /dev/null",
        "lineStart": 451,
        "lineEnd": 1120,
        "totalLines": 2108,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716612075,
      "end": 1793716612086
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d76bf9001l1g2PGXjs83Ork",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d76235001CrQLUvGxhTJyPU",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 72642,
    "input": 5518,
    "output": 27,
    "reasoning": 25,
    "cache": {
      "read": 67072,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d76235001CrQLUvGxhTJyPU",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716609589,
    "completed": 1793716612092
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 72642,
    "input": 5518,
    "output": 27,
    "reasoning": 25,
    "cache": {
      "read": 67072,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 33
step-start
{
  "type": "step-start",
  "id": "prt_1a1d77471001eIPVyA2QuwK4Df",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d76c04001vzNrO26VGTLzOG"
}
Reasoning
I have the diff for the source files. The startup_config diff shows only `_startup_config_commands` added and parse loop refactored — `filter_startup_config_blocks` existed in base (the diff context around line 43 shows the filter function unchanged). Good — so the FTNT_FORTIGUARD_HOOKS doc gap is pre-existing, not PR-introduced. Skip.

README.md diff: only the Startup Config paragraph updated — consistent with implementation. Good.

Now let me read the remaining test diffs (1117-2108) to see what changed in test files — mostly new files and additions. The three new files are entirely new. test_common_stack_boundaries.py and test_common_stack_parsing.py and test_common_terminal_driver.py are modified. Let me read the rest of the diff to see those changes.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 990,
  "offset": 1121
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1121: +++ b/fortinet/tests/test_common_admin_credentials.py
1122: @@ -0,0 +1,154 @@
1123: +"""Admin credential commits followed by logout and console authentication."""
1124: +
1125: +import sys
1126: +import unittest
1127: +from pathlib import Path
1128: +from types import SimpleNamespace
1129: +from unittest.mock import MagicMock, patch
1130: +
1131: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1132: +
1133: +from fortinet.common.common import Credentials
1134: +from fortinet.common.features.credentials import CredentialsFeature
1135: +from fortinet.common.fos_cli_driver import FOSCliDriver
1136: +from fortinet.common.fos_commander import FOSCommander
1137: +from fortinet.common.terminal import Terminal
1138: +from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection
1139: +
1140: +
1141: +LOGIN = b"fw login:\r\n"
1142: +READY = b"Welcome!\r\nfw #\r\n"
1143: +ADMIN_PROMPT = b"fw (admin) #\r\n"
1144: +
1145: +
1146: +class AdminCredentialsTests(unittest.TestCase):
1147: +    def make_stack(self, *, password="newpass", username="admin",
1148: +                   auto_logout=None, authenticate=True, reject=False,
1149: +                   exit_works=True):
1150: +        logger = MagicMock()
1151: +        policy_prompt = b"fw (password-policy) #\r\n"
1152: +        old_password_responses = [READY]
1153: +        if password:
1154: +            old_password_responses.append(ADMIN_PROMPT)
1155: +        old_password_responses.append(b"Login incorrect\r\n" + LOGIN)
1156: +        end_count = 0
1157: +
1158: +        def end_response():
1159: +            nonlocal end_count
1160: +            end_count += 1
1161: +            return LOGIN if auto_logout == "end" and end_count == 2 else b"fw #\r\n"
1162: +
1163: +        login_reply = None if not authenticate else (
1164: +            b"Login incorrect\r\n" + LOGIN if reject else READY
1165: +        )
1166: +        responses = {
1167: +            b"admin\r": b"Password:",
1168: +            b"oldpass\r": lambda: old_password_responses.pop(0),
1169: +            b"config system password-policy\r": policy_prompt,
1170: +            b"set status disable\r": policy_prompt,
1171: +            b"config system admin\r": ADMIN_PROMPT,
1172: +            f"edit {username}\r".encode(): ADMIN_PROMPT,
1173: +            b"set accprofile super_admin\r": ADMIN_PROMPT,
1174: +            b"next\r": LOGIN if auto_logout == "next" else ADMIN_PROMPT,
1175: +            b"end\r": end_response,
1176: +            b"exit\r": LOGIN if exit_works else b"fw #\r\n",
1177: +            b"probe\r": b"fw #\r\n",
1178: +            (password + "\r").encode(): login_reply,
1179: +        }
1180: +        if username != "admin":
1181: +            responses[(username + "\r").encode()] = b"Password:"
1182: +        if password:
1183: +            responses[f"set password {password}\r".encode()] = (
1184: +                b"Please enter current administrator password: "
1185: +            )
1186: +        else:
1187: +            responses[b"unset password\r"] = ADMIN_PROMPT
1188: +
1189: +        connection = SerialConnection(responses)
1190: +        terminal = Terminal(connection, logger)
1191: +        commander = FOSCommander(terminal, logger)
1192: +        credentials = Credentials("admin", "oldpass")
1193: +        driver = FOSCliDriver(
1194: +            terminal, commander, credentials, logger, "bootstrap",
1195: +            MagicMock(), MagicMock(), allow_credential_recovery=True,
1196: +        )
1197: +
1198: +        def activate_desired():
1199: +            driver.remember_current_credentials()
1200: +            credentials.username = username
1201: +            credentials.password = password
1202: +
1203: +        vm = SimpleNamespace(
1204: +            desired_credentials=Credentials(username, password),
1205: +            activate_desired_credentials=activate_desired,
1206: +        )
1207: +        admin = CredentialsFeature(vm, commander)
1208: +        following = RecordingFeature(commander, "following", ["probe"])
1209: +        commander.start([admin, following])
1210: +        self.addCleanup(lambda: terminal.close() if not connection.closed else None)
1211: +        return connection, commander, driver, admin, following
1212: +
1213: +    def run_driver(self, driver):
1214: +        with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
1215: +                patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.15):
1216: +            driver.process_state()
1217: +
1218: +    def test_logout_and_relogin_after_committing_credentials(self):
1219: +        for username, password in (("admin", "newpass"), ("admin", ""),
1220: +                                   ("operator", "newpass")):
1221: +            with self.subTest(username=username, password_set=bool(password)):
1222: +                conn, cmd, driver, admin, following = self.make_stack(
1223: +                    username=username, password=password,
1224: +                )
1225: +                self.run_driver(driver)
1226: +                self.assertTrue(cmd.ready)
1227: +                self.assertTrue(admin.completed)
1228: +                self.assertTrue(following.completed)
1229: +                logout = conn.writes.index(b"exit\r")
1230: +                self.assertEqual(conn.writes[logout - 1], b"end\r")
1231: +                self.assertEqual(conn.writes[logout + 1:], [
1232: +                    (username + "\r").encode(),
1233: +                    (password + "\r").encode(),
1234: +                    b"probe\r",
1235: +                ])
1236: +                self.assertEqual(conn.writes.count(b"exit\r"), 1)
1237: +
1238: +    def test_later_features_wait_for_authentication(self):
1239: +        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)
1240: +        self.run_driver(driver)
1241: +        self.assertIn(b"exit\r", conn.writes)
1242: +        self.assertIn(b"newpass\r", conn.writes)
1243: +        self.assertNotIn(b"probe\r", conn.writes)
1244: +        self.assertFalse(admin.completed)
1245: +        self.assertFalse(following.completed)
1246: +        self.assertFalse(cmd.ready)
1247: +
1248: +    def test_fortios_logout_at_commit_does_not_replay_password_change(self):
1249: +        for commit_command in ("next", "end"):
1250: +            with self.subTest(commit_command=commit_command):
1251: +                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)
1252: +                self.run_driver(driver)
1253: +                self.assertTrue(cmd.ready)
1254: +                self.assertTrue(admin.completed)
1255: +                self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
1256: +                self.assertEqual(conn.writes.count(b"exit\r"), 1)
1257: +                self.assertEqual(conn.writes.count(b"newpass\r"), 2)
1258: +
1259: +    def test_logout_must_return_to_login(self):
1260: +        conn, _, driver, admin, _ = self.make_stack(exit_works=False)
1261: +        with self.assertRaisesRegex(RuntimeError, "expected PROVIDE_USERNAME"):
1262: +            self.run_driver(driver)
1263: +        self.assertFalse(admin.completed)
1264: +        self.assertNotIn(b"probe\r", conn.writes)
1265: +
1266: +    def test_rejected_credentials_do_not_start_later_features(self):
1267: +        conn, _, driver, admin, _ = self.make_stack(reject=True)
1268: +        with self.assertRaisesRegex(RuntimeError, "Credential rejected"):
1269: +            self.run_driver(driver)
1270: +        self.assertFalse(admin.completed)
1271: +        self.assertNotIn(b"probe\r", conn.writes)
1272: +        self.assertEqual(conn.writes.count(b"set password newpass\r"), 1)
1273: +
1274: +
1275: +if __name__ == "__main__":
1276: +    unittest.main()
1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py
1278: new file mode 100644
1279: index 0000000..2afb43a
1280: --- /dev/null
1281: +++ b/fortinet/tests/test_common_recovery.py
1282: @@ -0,0 +1,292 @@
1283: +"""Bounded recovery after a scope exit or an interrupted CLI session."""
1284: +
1285: +import sys
1286: +import unittest
1287: +from pathlib import Path
1288: +from unittest.mock import MagicMock
1289: +
1290: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1291: +
1292: +from fortinet.common.cli_commands import (  # noqa: E402
1293: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,
1294: +    EditBlock, SessionLossAction,
1295: +)
1296: +from fortinet.common.common import FOSCliState  # noqa: E402
1297: +from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402
1298: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1299: +from fortinet.common.terminal import Data  # noqa: E402
1300: +
1301: +
1302: +IP_COMMAND = "set ip 10.0.52.4/24"
1303: +ACCESS_COMMAND = "set allowaccess ping https ssh http"
1304: +
1305: +
1306: +class RecordingFeature(Feature):
1307: +    def __init__(self, commander, block, context_action=None):
1308: +        super().__init__(None, commander, "management")
1309: +        self.block = block
1310: +        self.context_action = context_action
1311: +        self.losses = []
1312: +        self.attempts = []
1313: +        self.executed = []
1314: +
1315: +    def activate(self):
1316: +        self.commander.submit_block(self, self.block)
1317: +
1318: +    def on_command_dispatched(self, attempt):
1319: +        super().on_command_dispatched(attempt)
1320: +        self.attempts.append(attempt)
1321: +
1322: +    def on_command_executed(self, attempt, state):
1323: +        self.executed.append(attempt.spec.line)
1324: +
1325: +    def on_context_loss(self, attempt):
1326: +        self.losses.append(attempt)
1327: +        if self.context_action is not None:
1328: +            return self.context_action
1329: +        return super().on_context_loss(attempt)
1330: +
1331: +
1332: +class RecoveryTests(unittest.TestCase):
1333: +    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,
1334: +                       context_action=None, following=False):
1335: +        terminal = MagicMock()
1336: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error)
1337: +        block = ConfigBlock("system interface", [EditBlock("port1", [
1338: +            ip_command, ACCESS_COMMAND,
1339: +        ])])
1340: +        feature = RecordingFeature(commander, block, context_action)
1341: +        features = [feature]
1342: +        if following:
1343: +            features.append(RecordingFeature(
1344: +                commander, CommandSequence("following", ["get system status"])
1345: +            ))
1346: +        commander.start(features)
1347: +        return commander, terminal, feature
1348: +
1349: +    def prompt(self, commander, context=None):
1350: +        scope = f" ({context})" if context else ""
1351: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(
1352: +            f"FGT-VM64-KVM-NSVHDM{scope} (Interim)#".encode()
1353: +        ))
1354: +
1355: +    def enter_interface(self, commander):
1356: +        self.prompt(commander, "interface")
1357: +        self.prompt(commander, "port1")
1358: +
1359: +    def finish_interface(self, commander):
1360: +        self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
1361: +        self.prompt(commander, "port1")  # allowaccess succeeds; dispatch next.
1362: +        self.prompt(commander, "interface")  # next succeeds; dispatch end.
1363: +        self.prompt(commander)  # end succeeds.
1364: +
1365: +    @staticmethod
1366: +    def writes(terminal):
1367: +        return [call.args[0] for call in terminal.write.call_args_list]
1368: +
1369: +    def reconnect(self, commander):
1370: +        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b"Welcome!"))
1371: +        self.prompt(commander)
1372: +
1373: +    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):
1374: +        commander, terminal, feature = self.make_commander()
1375: +        self.prompt(commander)
1376: +        self.enter_interface(commander)
1377: +        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.
1378: +        self.assertEqual(self.writes(terminal), [
1379: +            "config system interface\r", "edit port1\r", IP_COMMAND + "\r",
1380: +            "config system interface\r",
1381: +        ])
1382: +        self.assertNotIn(IP_COMMAND, feature.executed)
1383: +        self.assertEqual(feature.losses[0].prompt_context_before, ("port1", "Interim"))
1384: +        self.assertEqual(feature.losses[0].prompt_context_after, ("Interim",))
1385: +        self.enter_interface(commander)
1386: +        self.finish_interface(commander)
1387: +        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]
1388: +        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])
1389: +        self.assertTrue(feature.completed)
1390: +        self.assertTrue(commander.ready)
1391: +
1392: +    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):
1393: +        for best_effort in (False, True):
1394: +            with self.subTest(best_effort=best_effort):
1395: +                commander, terminal, feature = self.make_commander(
1396: +                    continue_on_error=best_effort, following=True,
1397: +                )
1398: +                self.prompt(commander)
1399: +                self.enter_interface(commander)
1400: +                self.prompt(commander)
1401: +                self.enter_interface(commander)
1402: +                if best_effort:
1403: +                    self.prompt(commander)
1404: +                    self.assertIn("retry limit", commander.feature_errors[0][1])
1405: +                    self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1406: +                else:
1407: +                    with self.assertRaisesRegex(RuntimeError, "retry limit"):
1408: +                        self.prompt(commander)
1409: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
1410: +                self.assertNotIn(ACCESS_COMMAND + "\r", self.writes(terminal))
1411: +                self.assertFalse(feature.completed)
1412: +
1413: +    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):
1414: +        commander, terminal, feature = self.make_commander()
1415: +        self.prompt(commander)
1416: +        self.enter_interface(commander)
1417: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1418: +        self.reconnect(commander)
1419: +        self.enter_interface(commander)
1420: +        with self.assertRaisesRegex(RuntimeError, "retry limit"):
1421: +            self.prompt(commander)
1422: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 2)
1423: +        self.assertEqual(feature.losses[0].retry_count, 1)
1424: +
1425: +    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):
1426: +        commander, terminal, _feature = self.make_commander(
1427: +            continue_on_error=True, following=True,
1428: +        )
1429: +        self.prompt(commander)
1430: +        self.enter_interface(commander)
1431: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1432: +        self.reconnect(commander)
1433: +        self.enter_interface(commander)
1434: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
1435: +        self.assertNotIn("get system status\r", self.writes(terminal))
1436: +        self.reconnect(commander)
1437: +        self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1438: +        self.assertIn("retry limit", commander.feature_errors[0][1])
1439: +
1440: +    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):
1441: +        commander, terminal, _feature = self.make_commander(
1442: +            continue_on_error=True, following=True,
1443: +        )
1444: +        self.prompt(commander)
1445: +        self.enter_interface(commander)
1446: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1447: +        self.prompt(commander)  # Successful login returns a prompt, no Welcome.
1448: +        self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
1449: +        self.enter_interface(commander)
1450: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost again"))
1451: +        self.assertNotIn("get system status\r", self.writes(terminal))
1452: +        self.prompt(commander)  # Exhaustion is handled at this usable prompt.
1453: +        self.assertEqual(self.writes(terminal)[-1], "get system status\r")
1454: +        self.assertIn("retry limit", commander.feature_errors[0][1])
1455: +
1456: +    def test_each_command_position_gets_one_recovery(self):
1457: +        commander, terminal, feature = self.make_commander()
1458: +        self.prompt(commander)
1459: +        self.enter_interface(commander)
1460: +        self.prompt(commander)  # First loss: IP command.
1461: +        self.enter_interface(commander)
1462: +        self.prompt(commander, "port1")  # IP succeeds; dispatch allowaccess.
1463: +        self.prompt(commander)  # Second loss: allowaccess command.
1464: +        self.enter_interface(commander)
1465: +        self.finish_interface(commander)
1466: +        self.assertTrue(feature.completed)
1467: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 3)
1468: +        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + "\r"), 2)
1469: +
1470: +    def test_feature_can_decline_replay_without_running_session_loss_callback(self):
1471: +        for explicit_policy in (False, True):
1472: +            with self.subTest(explicit_policy=explicit_policy):
1473: +                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)
1474: +                commander, terminal, feature = self.make_commander(
1475: +                    ip_command=IP_COMMAND if explicit_policy else spec,
1476: +                    context_action=ContextLossAction.FAIL if explicit_policy else None,
1477: +                )
1478: +                feature.on_session_loss = MagicMock()
1479: +                self.prompt(commander)
1480: +                self.enter_interface(commander)
1481: +                with self.assertRaisesRegex(RuntimeError, "feature declined replay"):
1482: +                    self.prompt(commander)
1483: +                feature.on_session_loss.assert_not_called()
1484: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
1485: +
1486: +    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):
1487: +        spec = CommandSpec(
1488: +            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,
1489: +            context_loss=ContextLossAction.RESTART_BLOCK,
1490: +        )
1491: +        commander, _terminal, feature = self.make_commander(ip_command=spec)
1492: +        feature.on_session_loss = MagicMock()
1493: +        self.prompt(commander)
1494: +        self.enter_interface(commander)
1495: +        self.prompt(commander)
1496: +        self.enter_interface(commander)
1497: +        self.finish_interface(commander)
1498: +        self.assertTrue(feature.completed)
1499: +        feature.on_session_loss.assert_not_called()
1500: +
1501: +    def test_partial_scope_is_aborted_once_before_replay(self):
1502: +        commander, terminal, feature = self.make_commander()
1503: +        self.prompt(commander)
1504: +        self.enter_interface(commander)
1505: +        self.prompt(commander, "interface")  # Only the edit context disappeared.
1506: +        self.assertEqual(self.writes(terminal)[-1], "abort\r")
1507: +        self.prompt(commander)
1508: +        self.assertEqual(self.writes(terminal)[-1], "config system interface\r")
1509: +        self.enter_interface(commander)
1510: +        self.finish_interface(commander)
1511: +        self.assertTrue(feature.completed)
1512: +        self.assertNotIn("abort", feature.executed)
1513: +        self.assertNotIn("abort", [item.spec.line for item in feature.attempts])
1514: +
1515: +    def test_failed_context_reset_does_not_loop(self):
1516: +        commander, terminal, _feature = self.make_commander()
1517: +        self.prompt(commander)
1518: +        self.enter_interface(commander)
1519: +        self.prompt(commander, "interface")
1520: +        with self.assertRaisesRegex(RuntimeError, "Unable to restore CLI context"):
1521: +            self.prompt(commander, "interface")
1522: +        self.assertEqual(self.writes(terminal).count("abort\r"), 1)
1523: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + "\r"), 1)
1524: +
1525: +    def test_session_loss_during_context_reset_resumes_after_login(self):
1526: +        commander, terminal, feature = self.make_commander()
1527: +        self.prompt(commander)
1528: +        self.enter_interface(commander)
1529: +        self.prompt(commander, "interface")
1530: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1531: +        self.reconnect(commander)
1532: +        self.enter_interface(commander)
1533: +        self.finish_interface(commander)
1534: +        self.assertTrue(feature.completed)
1535: +        self.assertEqual(self.writes(terminal).count("abort\r"), 1)
1536: +
1537: +    def test_cleanup_session_loss_is_bounded(self):
1538: +        terminal = MagicMock()
1539: +        commander = FOSCommander(terminal, MagicMock())
1540: +        feature = RecordingFeature(commander, CommandSequence("work", ["get status"]))
1541: +        commander.register_cleanup(feature, CleanupAction(
1542: +            "cleanup", CommandSequence("cleanup", ["get cleanup"]),
1543: +        ))
1544: +        commander.start([feature])
1545: +        self.prompt(commander)
1546: +        self.prompt(commander)  # Begin cleanup after the feature completes.
1547: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1548: +        self.reconnect(commander)
1549: +        with self.assertRaisesRegex(RuntimeError, "retry limit"):
1550: +            commander.on_state(FOSCliState.SESSION_LOST, Data(b"session lost"))
1551: +        self.assertEqual(self.writes(terminal).count("get cleanup\r"), 2)
1552: +
1553: +    def test_newly_submitted_block_resets_retry_allowance(self):
1554: +        terminal = MagicMock()
1555: +        commander = FOSCommander(terminal, MagicMock())
1556: +        feature = StaticFeature(None, commander, "two-blocks", [
1557: +            ConfigBlock("system global", ["set alias first"]),
1558: +            ConfigBlock("system global", ["set alias second"]),
1559: +        ])
1560: +        commander.start([feature])
1561: +        self.prompt(commander)
1562: +        for _index in range(2):
1563: +            self.prompt(commander, "global")
1564: +            self.prompt(commander)  # Lost context: retry this block.
1565: +            self.prompt(commander, "global")
1566: +            self.prompt(commander, "global")
1567: +            self.prompt(commander)  # End this block and start the next one.
1568: +        self.assertTrue(feature.completed)
1569: +        self.assertEqual(self.writes(terminal).count("set alias first\r"), 2)
1570: +        self.assertEqual(self.writes(terminal).count("set alias second\r"), 2)
1571: +
1572: +
1573: +if __name__ == "__main__":
1574: +    unittest.main()
1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py
1576: new file mode 100644
1577: index 0000000..56ce729
1578: --- /dev/null
1579: +++ b/fortinet/tests/test_common_scope_errors.py
1580: @@ -0,0 +1,154 @@
1581: +"""Scope commit failures are mandatory errors, including best-effort commands."""
1582: +
1583: +import sys
1584: +import unittest
1585: +from pathlib import Path
1586: +from unittest.mock import MagicMock
1587: +
1588: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
1589: +
1590: +from fortinet.common.cli_commands import (  # noqa: E402
1591: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,
1592: +)
1593: +from fortinet.common.common import FOSCliState  # noqa: E402
1594: +from fortinet.common.features.base import Feature  # noqa: E402
1595: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1596: +from fortinet.common.terminal import Data  # noqa: E402
1597: +
1598: +
1599: +class RecordingFeature(Feature):
1600: +    def __init__(self, commander, name, commands):
1601: +        super().__init__(None, commander, name)
1602: +        self.commands = commands
1603: +        self.executed = []
1604: +
1605: +    def activate(self):
1606: +        self.commander.submit_block(self, CommandSequence(self.name, self.commands))
1607: +
1608: +    def on_command_executed(self, attempt, state):
1609: +        self.executed.append(attempt.spec.line)
1610: +
1611: +
1612: +class ScopeCommitFailureTests(unittest.TestCase):
1613: +    @staticmethod
1614: +    def prompt(commander, context=None, output=b""):
1615: +        scope = f" ({context})" if context else ""
1616: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(
1617: +            output + f"fw{scope} #".encode()
1618: +        ))
1619: +
1620: +    @staticmethod
1621: +    def writes(terminal):
1622: +        return [call.args[0] for call in terminal.write.call_args_list]
1623: +
1624: +    def test_closing_failure_cannot_be_disabled_or_replayed(self):
1625: +        for close in ("next", "end"):
1626: +            for capture in (False, True):
1627: +                for best_effort in (False, True):
1628: +                    with self.subTest(close=close, capture=capture, best_effort=best_effort):
1629: +                        terminal = MagicMock()
1630: +                        commander = FOSCommander(terminal, MagicMock(), best_effort)
1631: +                        feature = RecordingFeature(commander, "commit", [
1632: +                            CommandSpec(close, capture_output=capture, fail_on_error=False),
1633: +                            "set must-not-run 1",
1634: +                        ])
1635: +                        feature.on_context_loss = MagicMock()
1636: +                        following = RecordingFeature(commander, "following", ["get status"])
1637: +                        commander.start([feature, following])
1638: +                        self.prompt(commander, "port1")
1639: +                        # The failure code can span multiple serial reads.
1640: +                        for chunk in (b"Command fa", b"il. Return co", b"de -542.\r\n"):
1641: +                            data = Data(chunk)
1642: +                            commander.on_output(data)
1643: +                            self.assertTrue(data.discarded)
1644: +                        if best_effort:
1645: +                            self.prompt(commander, "interface")
1646: +                            self.assertEqual(self.writes(terminal), [close + "\r", "get status\r"])
1647: +                            self.assertEqual(commander.feature_errors[0][0], "commit")
1648: +                            self.assertIn("return code -542", commander.feature_errors[0][1])
1649: +                        else:
1650: +                            with self.assertRaisesRegex(RuntimeError, "return code -542"):
1651: +                                self.prompt(commander, "interface")
1652: +                            self.assertEqual(self.writes(terminal), [close + "\r"])
1653: +                        feature.on_context_loss.assert_not_called()
1654: +                        self.assertEqual(feature.executed, [])
1655: +                        self.assertFalse(feature.completed)
1656: +
1657: +    def test_closing_failure_with_same_prompt_still_ejects(self):
1658: +        for code in ("0", "7", "-61"):
1659: +            for suffix in ("", "."):
1660: +                with self.subTest(code=code, suffix=suffix):
1661: +                    terminal = MagicMock()
1662: +                    commander = FOSCommander(terminal, MagicMock())
1663: +                    feature = RecordingFeature(commander, "commit", ["next", "end"])
1664: +                    commander.start([feature])
1665: +                    self.prompt(commander, "port1")
1666: +                    with self.assertRaisesRegex(RuntimeError, f"return code {code}"):
1667: +                        self.prompt(
1668: +                            commander, "port1",
1669: +                            f"  Command fail. Return code {code}{suffix}\r\n".encode(),
1670: +                        )
1671: +                    self.assertEqual(self.writes(terminal), ["next\r"])
1672: +
1673: +    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):
1674: +        for capture in (False, True):
1675: +            with self.subTest(capture=capture):
1676: +                terminal = MagicMock()
1677: +                commander = FOSCommander(terminal, MagicMock())
1678: +                feature = RecordingFeature(commander, "configure", [
1679: +                    ConfigBlock("system interface", [EditBlock("port1", [
1680: +                        CommandSpec("set unsupported 1", capture_output=capture),
1681: +                    ])]),
1682: +                ])
1683: +                commander.start([feature])
1684: +                self.prompt(commander)
1685: +                self.prompt(commander, "interface")
1686: +                self.prompt(commander, "port1")
1687: +                self.prompt(commander, "port1", b"Command fail. Return code -61.\r\n")
1688: +                self.assertEqual(self.writes(terminal)[-1], "next\r")
1689: +                self.prompt(commander, "interface")
1690: +                self.prompt(commander)
1691: +                self.assertTrue(feature.completed)
1692: +                self.assertTrue(commander.ready)
1693: +                self.assertEqual(commander.feature_errors, ())
1694: +
1695: +    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):
1696: +        for best_effort in (False, True):
1697: +            with self.subTest(best_effort=best_effort):
1698: +                terminal = MagicMock()
1699: +                commander = FOSCommander(terminal, MagicMock(), best_effort)
1700: +                feature = RecordingFeature(commander, "work", ["get initial"])
1701: +                following = RecordingFeature(commander, "following", ["get status"])
1702: +                commander.register_cleanup(feature, CleanupAction(
1703: +                    "close", CommandSequence("close", ["end"]),
1704: +                ))
1705: +                commander.start([feature, following])
1706: +                self.prompt(commander)
1707: +                self.prompt(commander)
1708: +                self.assertEqual(self.writes(terminal)[-1], "end\r")
1709: +                if best_effort:
1710: +                    self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
1711: +                    self.assertEqual(commander.feature_errors[0][0], "cleanup")
1712: +                    self.assertEqual(self.writes(terminal)[-1], "get status\r")
1713: +                else:
1714: +                    with self.assertRaisesRegex(RuntimeError, "return code -5"):
1715: +                        self.prompt(commander, output=b"Command fail. Return code -5.\r\n")
1716: +                    self.assertNotIn("get status\r", self.writes(terminal))
1717: +
1718: +    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):
1719: +        terminal = MagicMock()
1720: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)
1721: +        feature = RecordingFeature(commander, "commit", [CommandSpec(
1722: +            "end", completion_states=(FOSCliState.CONFIRMATION,),
1723: +            expected_completion_state=FOSCliState.CMD_PROMPT,
1724: +        )])
1725: +        commander.start([feature])
1726: +        self.prompt(commander, "interface")
1727: +        with self.assertRaisesRegex(RuntimeError, "unexpected prompt"):
1728: +            commander.on_state(FOSCliState.CONFIRMATION, Data(b"Do you want to continue?"))
1729: +        self.assertEqual(self.writes(terminal), ["end\r"])
1730: +        self.assertFalse(feature.completed)
1731: +
1732: +
1733: +if __name__ == "__main__":
1734: +    unittest.main()
1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py
1736: index 1e31693..d633771 100644
1737: --- a/fortinet/tests/test_common_stack_boundaries.py
1738: +++ b/fortinet/tests/test_common_stack_boundaries.py
1739: @@ -38,15 +38,15 @@ class BoundaryFeature(Feature):
1740:  
1741:      def on_session_loss(self, attempt):
1742:          return SessionLossAction.CONTINUE
1743:  
1744:  
1745: -def make_stack(spec, response, *, allow_recovery=False):
1746: +def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b"fw #"):
1747:      logger = MagicMock()
1748:      connection = SerialConnection({
1749:          b"admin\r": b"Password:",
1750: -        b"secret\r": b"Welcome!\r\nfw #\r\n",
1751: +        b"secret\r": b"Welcome!\r\n" + initial_prompt + b"\r\n",
1752:          b"probe\r": response,
1753:      })
1754:      terminal = Terminal(connection, logger, default_wait="fw #")
1755:      commander = FOSCommander(terminal, logger)
1756:      feature = BoundaryFeature(commander, spec)
1757: @@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):
1758:      response = (
1759:          (prompt + " probe" + ending + "captured diagnostic" + ending + prompt + ending)
1760:          .encode()
1761:      )
1762:      spec = CommandSpec("probe", capture_output=True)
1763: -    connection, terminal, commander, driver, feature, states = make_stack(spec, response)
1764: +    connection, terminal, commander, driver, feature, states = make_stack(
1765: +        spec, response, initial_prompt=prompt.encode()
1766: +    )
1767:      try:
1768:          with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
1769:                  patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1770:              driver.process_state()
1771:          assert commander.ready
1772: @@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b"", *, recover=False):
1773:          completion = (state,)
1774:      connection, terminal, commander, driver, feature, states = make_stack(
1775:          CommandSpec("probe", completion_states=completion, capture_output=True),
1776:          response,
1777:          allow_recovery=recover,
1778: +        initial_prompt=b"fw (global) #" if state == FOSCliState.CMD_PROMPT_ECHO else b"fw #",
1779:      )
1780:      try:
1781:          with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.03), \
1782:                  patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1783:              driver.process_state()
1784: @@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):
1785:              self.assertFalse(feature.completed)
1786:              self.assertIn(b"garbage", bytes(feature.current_attempt.output))
1787:          finally:
1788:              terminal.close()
1789:  
1790: -    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):
1791: +    def test_idle_read_exposes_retained_prompt_newline(self):
1792:          connection, terminal, commander, driver, feature, states = make_stack(
1793:              CommandSpec("probe", capture_output=True), None
1794:          )
1795:          try:
1796:              with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.01), \
1797:                      patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 0.04):
1798:                  driver.process_state()
1799:              self.assertIn(FOSCliState.TN_TIMEOUT, states)
1800: -            self.assertEqual(bytes(feature.current_attempt.output), b"")
1801: +            # The login response ended with a newline after the matched CLI
1802: +            # prompt. Full-buffer timeout inspection exposes that real byte.
1803: +            self.assertEqual(bytes(feature.current_attempt.output), b"\n")
1804:              self.assertTrue(commander.busy)
1805:          finally:
1806:              terminal.close()
1807:  
1808:      def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):
1809:          command_echo = b"fw (global) # probe\r\n"
1810:          payload = b"config system dns\r\n set primary 1.1.1.1\r\nend\r\nfw (global) #\r\n"
1811:          response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])
1812:          connection, terminal, commander, driver, feature, states = make_stack(
1813: -            CommandSpec("probe", capture_output=True), response
1814: +            CommandSpec("probe", capture_output=True), response,
1815: +            initial_prompt=b"fw (global) #",
1816:          )
1817:          try:
1818:              with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
1819:                      patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
1820:                  driver.process_state()
1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py
1822: index 74d6ef7..56346ea 100644
1823: --- a/fortinet/tests/test_common_stack_parsing.py
1824: +++ b/fortinet/tests/test_common_stack_parsing.py
1825: @@ -7,11 +7,13 @@ from pathlib import Path
1826:  from unittest.mock import MagicMock
1827:  
1828:  REPO_ROOT = Path(__file__).resolve().parents[2]
1829:  sys.path.insert(0, str(REPO_ROOT))
1830:  
1831: -from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402
1832: +from fortinet.common.cli_commands import (  # noqa: E402
1833: +    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,
1834: +)
1835:  from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
1836:  from fortinet.common.features.base import Feature  # noqa: E402
1837:  from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
1838:  from fortinet.common.fos_commander import FOSCommander  # noqa: E402
1839:  from fortinet.common.terminal import Terminal  # noqa: E402
1840: @@ -35,10 +37,12 @@ class SerialConnection:
1841:  
1842:      def write(self, data):
1843:          data = bytes(data)
1844:          self.writes.append(data)
1845:          response = self._responses.get(data)
1846: +        if callable(response):
1847: +            response = response()
1848:          if response:
1849:              chunks = response if isinstance(response, (tuple, list)) else (response,)
1850:              for chunk in chunks:
1851:                  if chunk:
1852:                      self._incoming.put(bytes(chunk))
1853: @@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):
1854:          self.assertEqual(bytes(terminal._buffer), b"")
1855:  
1856:      def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):
1857:          responses = {
1858:              b"admin\r": b"Password:",
1859: -            b"secret\r": b"Welcome!\r\nfw #\r\n",
1860: +            b"secret\r": b"Welcome!\r\nfw (global) #\r\n",
1861:              b"get system status\r": (
1862:                  b"fw (global) # get system status\r\n"
1863:                  b"Version: FortiGate-VM64 v7.4.2,build2571\r\n"
1864:                  b"--More--\r\n"
1865:                  b"Serial-Number: FGVMTEST\r\n"
1866: @@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):
1867:          self.assertIn(b"FortiGate-VM64 v7.4.2,build2571", captured)
1868:          self.assertIn(b"Serial-Number: FGVMTEST", captured)
1869:          self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)
1870:          self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)
1871:  
1872: +    def test_aborted_interface_edit_recovers_through_serial_driver(self):
1873: +        ip_responses = iter([
1874: +            b"abort\r\nfw (Interim)#\r\n",
1875: +            b"fw (port1) (Interim)#\r\n",
1876: +        ])
1877: +        responses = {
1878: +            b"admin\r": b"Password:",
1879: +            b"secret\r": b"Welcome!\r\nfw (Interim)#\r\n",
1880: +            b"config system interface\r": b"fw (interface) (Interim)#\r\n",
1881: +            b"edit port1\r": b"fw (port1) (Interim)#\r\n",
1882: +            b"set ip 10.0.52.4/24\r": lambda: next(ip_responses),
1883: +            b"set allowaccess ping https ssh http\r": b"fw (port1) (Interim)#\r\n",
1884: +            b"next\r": b"fw (interface) (Interim)#\r\n",
1885: +            b"end\r": b"fw (Interim)#\r\n",
1886: +        }
1887: +        feature_ref = []
1888: +
1889: +        def configured(commander):
1890: +            feature = RecordingFeature(commander, "management", [
1891: +                ConfigBlock("system interface", [EditBlock("port1", [
1892: +                    "set ip 10.0.52.4/24", "set allowaccess ping https ssh http",
1893: +                ])]),
1894: +            ])
1895: +            feature_ref.append(feature)
1896: +            return [feature]
1897: +
1898: +        connection, terminal, commander, driver = self.make_stack(configured, responses)
1899: +        try:
1900: +            driver.process_state()
1901: +            self.assertTrue(commander.ready)
1902: +            self.assertTrue(feature_ref[0].completed)
1903: +            self.assertEqual(connection.writes, [
1904: +                b"admin\r", b"secret\r",
1905: +                b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
1906: +                b"config system interface\r", b"edit port1\r", b"set ip 10.0.52.4/24\r",
1907: +                b"set allowaccess ping https ssh http\r", b"next\r", b"end\r",
1908: +            ])
1909: +        finally:
1910: +            terminal.close()
1911: +
1912: +    def test_failed_next_ejects_before_end_through_serial_driver(self):
1913: +        responses = {
1914: +            b"admin\r": b"Password:",
1915: +            b"secret\r": b"Welcome!\r\nfw #\r\n",
1916: +            b"config system interface\r": b"fw (interface)#\r\n",
1917: +            b"edit port1\r": b"fw (port1)#\r\n",
1918: +            b"set unsupported 1\r": b"Command fail. Return code -61.\r\nfw (port1)#\r\n",
1919: +            b"next\r": (
1920: +                b"Command fa", b"il. Return code -5.\r\nfw (port1)#\r\n",
1921: +            ),
1922: +        }
1923: +        feature_ref = []
1924: +
1925: +        def configured(commander):
1926: +            feature = RecordingFeature(commander, "management", [
1927: +                ConfigBlock("system interface", [EditBlock("port1", ["set unsupported 1"])]),
1928: +            ])
1929: +            feature_ref.append(feature)
1930: +            return [feature]
1931: +
1932: +        connection, terminal, commander, driver = self.make_stack(configured, responses)
1933: +        try:
1934: +            with self.assertRaisesRegex(RuntimeError, "'next'.*return code -5"):
1935: +                driver.process_state()
1936: +            self.assertEqual(connection.writes, [
1937: +                b"admin\r", b"secret\r", b"config system interface\r",
1938: +                b"edit port1\r", b"set unsupported 1\r", b"next\r",
1939: +            ])
1940: +            self.assertFalse(feature_ref[0].completed)
1941: +            self.assertFalse(commander.ready)
1942: +        finally:
1943: +            terminal.close()
1944: +
1945:  
1946:  if __name__ == "__main__":
1947:      unittest.main()
1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py
1949: index 4c0a37b..be7eab4 100644
1950: --- a/fortinet/tests/test_common_terminal_driver.py
1951: +++ b/fortinet/tests/test_common_terminal_driver.py
1952: @@ -9,12 +9,16 @@ from contextlib import contextmanager
1953:  from unittest.mock import MagicMock, patch
1954:  
1955:  REPO_ROOT = __import__("pathlib").Path(__file__).resolve().parents[2]
1956:  sys.path.insert(0, str(REPO_ROOT))
1957:  
1958: -from fortinet.common.common import Credentials, FOSCliState  # noqa: E402
1959: -from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402
1960: +from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402
1961: +from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402
1962: +from fortinet.common.fos_cli_driver import (  # noqa: E402
1963: +    FOSCliDriver,
1964: +    KernelPanicError,
1965: +)
1966:  from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402
1967:  
1968:  
1969:  class ByteQueueTests(unittest.TestCase):
1970:      def test_put_get_close_timeout_and_failure(self):
1971: @@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):
1972:          terminal._buffer_limit = 5
1973:          with self.assertRaisesRegex(RuntimeError, "exceeded 5"):
1974:              terminal._enforce_buffer_limit()
1975:          terminal._logger.error.assert_called_once()
1976:  
1977: +    def test_timeout_preserves_partial_token_for_a_later_read(self):
1978: +        terminal = self.terminal_with_data(b"Login incor")
1979: +        pattern = rb"(?m)^Login incorrect\r?$"
1980: +        index, match, output = terminal.expect([pattern], timeout=0.001)
1981: +        self.assertEqual((index, match), (-1, None))
1982: +        self.assertEqual(bytes(output), b"Login incor")
1983: +        # Inspection without discard keeps the partial token, including when
1984: +        # another wait expires without receiving any more bytes.
1985: +        _, _, output = terminal.expect([pattern], timeout=0)
1986: +        self.assertEqual(bytes(output), b"Login incor")
1987: +        terminal._read_queue.put(b"rect\n")
1988: +        index, match, output = terminal.expect([pattern], timeout=0.1)
1989: +        self.assertEqual(index, 0)
1990: +        self.assertEqual(match.group(), b"Login incorrect")
1991: +        self.assertEqual(bytes(output), b"Login incorrect")
1992: +        self.assertEqual(bytes(terminal._buffer), b"\n")
1993: +
1994: +    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):
1995: +        terminal = self.terminal_with_data(b"Verifying pass")
1996: +        _, _, output = terminal.expect([b"fw #"], timeout=0.001)
1997: +        self.assertIsNone(re.search(rb"Verifying password", bytes(output)))
1998: +
1999: +        terminal._read_queue.put(b"word...\n")
2000: +        _, match, output = terminal.expect([b"fw #"], timeout=0.001)
2001: +        self.assertIsNone(match)
2002: +        self.assertIsNotNone(re.search(rb"Verifying password", bytes(output)))
2003: +        self.assertEqual(bytes(terminal._buffer), b"Verifying password...\n")
2004: +        output.discard()
2005: +        self.assertEqual(bytes(terminal._buffer), b"")
2006: +
2007: +    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):
2008: +        prefix = b"\nVerifying password...\n"
2009: +        chunk = b"admin\nadmin\n"
2010: +        terminal = self.terminal_with_data(chunk)
2011: +        terminal._buffer.extend(prefix)
2012: +
2013: +        _, _, output = terminal.expect([b"fw #"], timeout=0.001)
2014: +        self.assertEqual(bytes(output), prefix + chunk)
2015: +        attempt = CommandAttempt(CommandSpec("end"), 1, 0)
2016: +        attempt.on_output(output)
2017: +
2018: +        self.assertEqual(bytes(attempt.output), prefix + chunk)
2019: +        self.assertEqual(bytes(terminal._buffer), b"")
2020: +        terminal._logger.warning.assert_not_called()
2021: +
2022:      def test_suppression_is_nested_and_restores_context(self):
2023:          @contextmanager
2024:          def context():
2025:              events.append("enter")
2026:              try:
2027: @@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):
2028:          with self.assertRaisesRegex(OSError, "serial failed"):
2029:              queue.get(0)
2030:          logger.exception.assert_called_once()
2031:          with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}):
2032:              self.assertEqual(terminal_buffer_limit_bytes(), 32)
2033: -        with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "0"}):
2034: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "64", "FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}, clear=True):
2035: +            self.assertEqual(terminal_buffer_limit_bytes(), 64)
2036: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "0"}, clear=True):
2037:              with self.assertRaises(ValueError):
2038:                  terminal_buffer_limit_bytes()
2039:  
2040: +    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):
2041: +        for env_name in ("FTNT_LOG_RAW_SERIAL", "FOS_LOG_RAW_SERIAL"):
2042: +            with self.subTest(env_name=env_name):
2043: +                terminal = self.terminal_with_data(b"matched")
2044: +                with patch.dict("os.environ", {env_name: "true"}, clear=True):
2045: +                    terminal.expect([b"matched"], timeout=0.1)
2046: +                terminal._logger.log.assert_called_once_with(
2047: +                    TRACE_LEVEL,
2048: +                    "buffer: bytearray(b'matched')",
2049: +                )
2050: +
2051:  
2052:  class DriverTests(unittest.TestCase):
2053:      def make_driver(self, *, allow_recovery=False):
2054:          terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()
2055:          commander.ready = False
2056: @@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):
2057:          self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)
2058:          terminal.expect.return_value = (-1, None, Data(b""))
2059:          self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)
2060:          driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)
2061:  
2062: +    def test_retained_timeout_output_does_not_count_as_fresh_input(self):
2063: +        driver, _, _, logger, *_ = self.make_driver()
2064: +        terminal = Terminal(MagicMock(), logger)
2065: +        terminal._ensure_reader = lambda: None
2066: +        terminal._read_queue.put(b"partial token")
2067: +        driver._terminal = terminal
2068: +
2069: +        with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.001):
2070: +            state, output, matched = driver._next_state()
2071: +            self.assertEqual(state, FOSCliState.UNKNOWN)
2072: +            self.assertEqual(bytes(output), b"partial token")
2073: +            self.assertFalse(matched)
2074: +            state, output, matched = driver._next_state()
2075: +            self.assertEqual(state, FOSCliState.TN_TIMEOUT)
2076: +            self.assertEqual(bytes(output), b"partial token")
2077: +            self.assertFalse(matched)
2078: +
2079: +    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):
2080: +        driver, terminal, commander, *_ = self.make_driver()
2081: +        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]
2082: +        panic = (
2083: +            b"Kernel panic - not syncing: VFS: Unable to mount root fs\r\n"
2084: +            b"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\r\n"
2085: +        )
2086: +
2087: +        self.assertIsNone(
2088: +            re.search(
2089: +                pattern,
2090: +                b"Kernel panic - not syncing: VFS: Unable to mount root fs",
2091: +            )
2092: +        )
2093: +        match = re.search(pattern, panic)
2094: +        self.assertIsNotNone(match)
2095: +        terminal.expect.return_value = (
2096: +            FOSCliState.KERNEL_PANIC.value,
2097: +            match,
2098: +            Data(panic),
2099: +        )
2100: +
2101: +        with self.assertRaisesRegex(KernelPanicError, "Kernel panic detected"):
2102: +            driver.process_state()
2103: +
2104: +        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))
2105: +
2106:  
2107:  if __name__ == "__main__":
2108:      unittest.main()

(End of file - total 2108 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d779b80016GhGObaweKjoB5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d76c04001vzNrO26VGTLzOG",
  "callID": "call_5bf3950aaf73403f8c644340",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 990,
      "offset": 1121
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1121: +++ b/fortinet/tests/test_common_admin_credentials.py\n1122: @@ -0,0 +1,154 @@\n1123: +\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n1124: +\n1125: +import sys\n1126: +import unittest\n1127: +from pathlib import Path\n1128: +from types import SimpleNamespace\n1129: +from unittest.mock import MagicMock, patch\n1130: +\n1131: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1132: +\n1133: +from fortinet.common.common import Credentials\n1134: +from fortinet.common.features.credentials import CredentialsFeature\n1135: +from fortinet.common.fos_cli_driver import FOSCliDriver\n1136: +from fortinet.common.fos_commander import FOSCommander\n1137: +from fortinet.common.terminal import Terminal\n1138: +from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n1139: +\n1140: +\n1141: +LOGIN = b\"fw login:\\r\\n\"\n1142: +READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n1143: +ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n1144: +\n1145: +\n1146: +class AdminCredentialsTests(unittest.TestCase):\n1147: +    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n1148: +                   auto_logout=None, authenticate=True, reject=False,\n1149: +                   exit_works=True):\n1150: +        logger = MagicMock()\n1151: +        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n1152: +        old_password_responses = [READY]\n1153: +        if password:\n1154: +            old_password_responses.append(ADMIN_PROMPT)\n1155: +        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n1156: +        end_count = 0\n1157: +\n1158: +        def end_response():\n1159: +            nonlocal end_count\n1160: +            end_count += 1\n1161: +            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n1162: +\n1163: +        login_reply = None if not authenticate else (\n1164: +            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n1165: +        )\n1166: +        responses = {\n1167: +            b\"admin\\r\": b\"Password:\",\n1168: +            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n1169: +            b\"config system password-policy\\r\": policy_prompt,\n1170: +            b\"set status disable\\r\": policy_prompt,\n1171: +            b\"config system admin\\r\": ADMIN_PROMPT,\n1172: +            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n1173: +            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n1174: +            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n1175: +            b\"end\\r\": end_response,\n1176: +            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n1177: +            b\"probe\\r\": b\"fw #\\r\\n\",\n1178: +            (password + \"\\r\").encode(): login_reply,\n1179: +        }\n1180: +        if username != \"admin\":\n1181: +            responses[(username + \"\\r\").encode()] = b\"Password:\"\n1182: +        if password:\n1183: +            responses[f\"set password {password}\\r\".encode()] = (\n1184: +                b\"Please enter current administrator password: \"\n1185: +            )\n1186: +        else:\n1187: +            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n1188: +\n1189: +        connection = SerialConnection(responses)\n1190: +        terminal = Terminal(connection, logger)\n1191: +        commander = FOSCommander(terminal, logger)\n1192: +        credentials = Credentials(\"admin\", \"oldpass\")\n1193: +        driver = FOSCliDriver(\n1194: +            terminal, commander, credentials, logger, \"bootstrap\",\n1195: +            MagicMock(), MagicMock(), allow_credential_recovery=True,\n1196: +        )\n1197: +\n1198: +        def activate_desired():\n1199: +            driver.remember_current_credentials()\n1200: +            credentials.username = username\n1201: +            credentials.password = password\n1202: +\n1203: +        vm = SimpleNamespace(\n1204: +            desired_credentials=Credentials(username, password),\n1205: +            activate_desired_credentials=activate_desired,\n1206: +        )\n1207: +        admin = CredentialsFeature(vm, commander)\n1208: +        following = RecordingFeature(commander, \"following\", [\"probe\"])\n1209: +        commander.start([admin, following])\n1210: +        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n1211: +        return connection, commander, driver, admin, following\n1212: +\n1213: +    def run_driver(self, driver):\n1214: +        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n1215: +                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n1216: +            driver.process_state()\n1217: +\n1218: +    def test_logout_and_relogin_after_committing_credentials(self):\n1219: +        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n1220: +                                   (\"operator\", \"newpass\")):\n1221: +            with self.subTest(username=username, password_set=bool(password)):\n1222: +                conn, cmd, driver, admin, following = self.make_stack(\n1223: +                    username=username, password=password,\n1224: +                )\n1225: +                self.run_driver(driver)\n1226: +                self.assertTrue(cmd.ready)\n1227: +                self.assertTrue(admin.completed)\n1228: +                self.assertTrue(following.completed)\n1229: +                logout = conn.writes.index(b\"exit\\r\")\n1230: +                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n1231: +                self.assertEqual(conn.writes[logout + 1:], [\n1232: +                    (username + \"\\r\").encode(),\n1233: +                    (password + \"\\r\").encode(),\n1234: +                    b\"probe\\r\",\n1235: +                ])\n1236: +                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n1237: +\n1238: +    def test_later_features_wait_for_authentication(self):\n1239: +        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n1240: +        self.run_driver(driver)\n1241: +        self.assertIn(b\"exit\\r\", conn.writes)\n1242: +        self.assertIn(b\"newpass\\r\", conn.writes)\n1243: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1244: +        self.assertFalse(admin.completed)\n1245: +        self.assertFalse(following.completed)\n1246: +        self.assertFalse(cmd.ready)\n1247: +\n1248: +    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n1249: +        for commit_command in (\"next\", \"end\"):\n1250: +            with self.subTest(commit_command=commit_command):\n1251: +                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n1252: +                self.run_driver(driver)\n1253: +                self.assertTrue(cmd.ready)\n1254: +                self.assertTrue(admin.completed)\n1255: +                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n1256: +                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n1257: +                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n1258: +\n1259: +    def test_logout_must_return_to_login(self):\n1260: +        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n1261: +        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n1262: +            self.run_driver(driver)\n1263: +        self.assertFalse(admin.completed)\n1264: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1265: +\n1266: +    def test_rejected_credentials_do_not_start_later_features(self):\n1267: +        conn, _, driver, admin, _ = self.make_stack(reject=True)\n1268: +        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n1269: +            self.run_driver(driver)\n1270: +        self.assertFalse(admin.completed)\n1271: +        self.assertNotIn(b\"probe\\r\", conn.writes)\n1272: +        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n1273: +\n1274: +\n1275: +if __name__ == \"__main__\":\n1276: +    unittest.main()\n1277: diff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\n1278: new file mode 100644\n1279: index 0000000..2afb43a\n1280: --- /dev/null\n1281: +++ b/fortinet/tests/test_common_recovery.py\n1282: @@ -0,0 +1,292 @@\n1283: +\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n1284: +\n1285: +import sys\n1286: +import unittest\n1287: +from pathlib import Path\n1288: +from unittest.mock import MagicMock\n1289: +\n1290: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1291: +\n1292: +from fortinet.common.cli_commands import (  # noqa: E402\n1293: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n1294: +    EditBlock, SessionLossAction,\n1295: +)\n1296: +from fortinet.common.common import FOSCliState  # noqa: E402\n1297: +from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n1298: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1299: +from fortinet.common.terminal import Data  # noqa: E402\n1300: +\n1301: +\n1302: +IP_COMMAND = \"set ip 10.0.52.4/24\"\n1303: +ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n1304: +\n1305: +\n1306: +class RecordingFeature(Feature):\n1307: +    def __init__(self, commander, block, context_action=None):\n1308: +        super().__init__(None, commander, \"management\")\n1309: +        self.block = block\n1310: +        self.context_action = context_action\n1311: +        self.losses = []\n1312: +        self.attempts = []\n1313: +        self.executed = []\n1314: +\n1315: +    def activate(self):\n1316: +        self.commander.submit_block(self, self.block)\n1317: +\n1318: +    def on_command_dispatched(self, attempt):\n1319: +        super().on_command_dispatched(attempt)\n1320: +        self.attempts.append(attempt)\n1321: +\n1322: +    def on_command_executed(self, attempt, state):\n1323: +        self.executed.append(attempt.spec.line)\n1324: +\n1325: +    def on_context_loss(self, attempt):\n1326: +        self.losses.append(attempt)\n1327: +        if self.context_action is not None:\n1328: +            return self.context_action\n1329: +        return super().on_context_loss(attempt)\n1330: +\n1331: +\n1332: +class RecoveryTests(unittest.TestCase):\n1333: +    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n1334: +                       context_action=None, following=False):\n1335: +        terminal = MagicMock()\n1336: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n1337: +        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1338: +            ip_command, ACCESS_COMMAND,\n1339: +        ])])\n1340: +        feature = RecordingFeature(commander, block, context_action)\n1341: +        features = [feature]\n1342: +        if following:\n1343: +            features.append(RecordingFeature(\n1344: +                commander, CommandSequence(\"following\", [\"get system status\"])\n1345: +            ))\n1346: +        commander.start(features)\n1347: +        return commander, terminal, feature\n1348: +\n1349: +    def prompt(self, commander, context=None):\n1350: +        scope = f\" ({context})\" if context else \"\"\n1351: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n1352: +            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n1353: +        ))\n1354: +\n1355: +    def enter_interface(self, commander):\n1356: +        self.prompt(commander, \"interface\")\n1357: +        self.prompt(commander, \"port1\")\n1358: +\n1359: +    def finish_interface(self, commander):\n1360: +        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n1361: +        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n1362: +        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n1363: +        self.prompt(commander)  # end succeeds.\n1364: +\n1365: +    @staticmethod\n1366: +    def writes(terminal):\n1367: +        return [call.args[0] for call in terminal.write.call_args_list]\n1368: +\n1369: +    def reconnect(self, commander):\n1370: +        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n1371: +        self.prompt(commander)\n1372: +\n1373: +    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n1374: +        commander, terminal, feature = self.make_commander()\n1375: +        self.prompt(commander)\n1376: +        self.enter_interface(commander)\n1377: +        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n1378: +        self.assertEqual(self.writes(terminal), [\n1379: +            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n1380: +            \"config system interface\\r\",\n1381: +        ])\n1382: +        self.assertNotIn(IP_COMMAND, feature.executed)\n1383: +        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n1384: +        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n1385: +        self.enter_interface(commander)\n1386: +        self.finish_interface(commander)\n1387: +        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n1388: +        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n1389: +        self.assertTrue(feature.completed)\n1390: +        self.assertTrue(commander.ready)\n1391: +\n1392: +    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n1393: +        for best_effort in (False, True):\n1394: +            with self.subTest(best_effort=best_effort):\n1395: +                commander, terminal, feature = self.make_commander(\n1396: +                    continue_on_error=best_effort, following=True,\n1397: +                )\n1398: +                self.prompt(commander)\n1399: +                self.enter_interface(commander)\n1400: +                self.prompt(commander)\n1401: +                self.enter_interface(commander)\n1402: +                if best_effort:\n1403: +                    self.prompt(commander)\n1404: +                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1405: +                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1406: +                else:\n1407: +                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1408: +                        self.prompt(commander)\n1409: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n1410: +                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n1411: +                self.assertFalse(feature.completed)\n1412: +\n1413: +    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n1414: +        commander, terminal, feature = self.make_commander()\n1415: +        self.prompt(commander)\n1416: +        self.enter_interface(commander)\n1417: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1418: +        self.reconnect(commander)\n1419: +        self.enter_interface(commander)\n1420: +        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1421: +            self.prompt(commander)\n1422: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n1423: +        self.assertEqual(feature.losses[0].retry_count, 1)\n1424: +\n1425: +    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n1426: +        commander, terminal, _feature = self.make_commander(\n1427: +            continue_on_error=True, following=True,\n1428: +        )\n1429: +        self.prompt(commander)\n1430: +        self.enter_interface(commander)\n1431: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1432: +        self.reconnect(commander)\n1433: +        self.enter_interface(commander)\n1434: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n1435: +        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n1436: +        self.reconnect(commander)\n1437: +        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1438: +        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1439: +\n1440: +    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n1441: +        commander, terminal, _feature = self.make_commander(\n1442: +            continue_on_error=True, following=True,\n1443: +        )\n1444: +        self.prompt(commander)\n1445: +        self.enter_interface(commander)\n1446: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1447: +        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n1448: +        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n1449: +        self.enter_interface(commander)\n1450: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n1451: +        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n1452: +        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n1453: +        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n1454: +        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n1455: +\n1456: +    def test_each_command_position_gets_one_recovery(self):\n1457: +        commander, terminal, feature = self.make_commander()\n1458: +        self.prompt(commander)\n1459: +        self.enter_interface(commander)\n1460: +        self.prompt(commander)  # First loss: IP command.\n1461: +        self.enter_interface(commander)\n1462: +        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n1463: +        self.prompt(commander)  # Second loss: allowaccess command.\n1464: +        self.enter_interface(commander)\n1465: +        self.finish_interface(commander)\n1466: +        self.assertTrue(feature.completed)\n1467: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n1468: +        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n1469: +\n1470: +    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n1471: +        for explicit_policy in (False, True):\n1472: +            with self.subTest(explicit_policy=explicit_policy):\n1473: +                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n1474: +                commander, terminal, feature = self.make_commander(\n1475: +                    ip_command=IP_COMMAND if explicit_policy else spec,\n1476: +                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n1477: +                )\n1478: +                feature.on_session_loss = MagicMock()\n1479: +                self.prompt(commander)\n1480: +                self.enter_interface(commander)\n1481: +                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n1482: +                    self.prompt(commander)\n1483: +                feature.on_session_loss.assert_not_called()\n1484: +                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n1485: +\n1486: +    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n1487: +        spec = CommandSpec(\n1488: +            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n1489: +            context_loss=ContextLossAction.RESTART_BLOCK,\n1490: +        )\n1491: +        commander, _terminal, feature = self.make_commander(ip_command=spec)\n1492: +        feature.on_session_loss = MagicMock()\n1493: +        self.prompt(commander)\n1494: +        self.enter_interface(commander)\n1495: +        self.prompt(commander)\n1496: +        self.enter_interface(commander)\n1497: +        self.finish_interface(commander)\n1498: +        self.assertTrue(feature.completed)\n1499: +        feature.on_session_loss.assert_not_called()\n1500: +\n1501: +    def test_partial_scope_is_aborted_once_before_replay(self):\n1502: +        commander, terminal, feature = self.make_commander()\n1503: +        self.prompt(commander)\n1504: +        self.enter_interface(commander)\n1505: +        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n1506: +        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n1507: +        self.prompt(commander)\n1508: +        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n1509: +        self.enter_interface(commander)\n1510: +        self.finish_interface(commander)\n1511: +        self.assertTrue(feature.completed)\n1512: +        self.assertNotIn(\"abort\", feature.executed)\n1513: +        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n1514: +\n1515: +    def test_failed_context_reset_does_not_loop(self):\n1516: +        commander, terminal, _feature = self.make_commander()\n1517: +        self.prompt(commander)\n1518: +        self.enter_interface(commander)\n1519: +        self.prompt(commander, \"interface\")\n1520: +        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n1521: +            self.prompt(commander, \"interface\")\n1522: +        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n1523: +        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n1524: +\n1525: +    def test_session_loss_during_context_reset_resumes_after_login(self):\n1526: +        commander, terminal, feature = self.make_commander()\n1527: +        self.prompt(commander)\n1528: +        self.enter_interface(commander)\n1529: +        self.prompt(commander, \"interface\")\n1530: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1531: +        self.reconnect(commander)\n1532: +        self.enter_interface(commander)\n1533: +        self.finish_interface(commander)\n1534: +        self.assertTrue(feature.completed)\n1535: +        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n1536: +\n1537: +    def test_cleanup_session_loss_is_bounded(self):\n1538: +        terminal = MagicMock()\n1539: +        commander = FOSCommander(terminal, MagicMock())\n1540: +        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n1541: +        commander.register_cleanup(feature, CleanupAction(\n1542: +            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n1543: +        ))\n1544: +        commander.start([feature])\n1545: +        self.prompt(commander)\n1546: +        self.prompt(commander)  # Begin cleanup after the feature completes.\n1547: +        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1548: +        self.reconnect(commander)\n1549: +        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n1550: +            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n1551: +        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n1552: +\n1553: +    def test_newly_submitted_block_resets_retry_allowance(self):\n1554: +        terminal = MagicMock()\n1555: +        commander = FOSCommander(terminal, MagicMock())\n1556: +        feature = StaticFeature(None, commander, \"two-blocks\", [\n1557: +            ConfigBlock(\"system global\", [\"set alias first\"]),\n1558: +            ConfigBlock(\"system global\", [\"set alias second\"]),\n1559: +        ])\n1560: +        commander.start([feature])\n1561: +        self.prompt(commander)\n1562: +        for _index in range(2):\n1563: +            self.prompt(commander, \"global\")\n1564: +            self.prompt(commander)  # Lost context: retry this block.\n1565: +            self.prompt(commander, \"global\")\n1566: +            self.prompt(commander, \"global\")\n1567: +            self.prompt(commander)  # End this block and start the next one.\n1568: +        self.assertTrue(feature.completed)\n1569: +        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n1570: +        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n1571: +\n1572: +\n1573: +if __name__ == \"__main__\":\n1574: +    unittest.main()\n1575: diff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\n1576: new file mode 100644\n1577: index 0000000..56ce729\n1578: --- /dev/null\n1579: +++ b/fortinet/tests/test_common_scope_errors.py\n1580: @@ -0,0 +1,154 @@\n1581: +\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n1582: +\n1583: +import sys\n1584: +import unittest\n1585: +from pathlib import Path\n1586: +from unittest.mock import MagicMock\n1587: +\n1588: +sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n1589: +\n1590: +from fortinet.common.cli_commands import (  # noqa: E402\n1591: +    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n1592: +)\n1593: +from fortinet.common.common import FOSCliState  # noqa: E402\n1594: +from fortinet.common.features.base import Feature  # noqa: E402\n1595: +from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1596: +from fortinet.common.terminal import Data  # noqa: E402\n1597: +\n1598: +\n1599: +class RecordingFeature(Feature):\n1600: +    def __init__(self, commander, name, commands):\n1601: +        super().__init__(None, commander, name)\n1602: +        self.commands = commands\n1603: +        self.executed = []\n1604: +\n1605: +    def activate(self):\n1606: +        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n1607: +\n1608: +    def on_command_executed(self, attempt, state):\n1609: +        self.executed.append(attempt.spec.line)\n1610: +\n1611: +\n1612: +class ScopeCommitFailureTests(unittest.TestCase):\n1613: +    @staticmethod\n1614: +    def prompt(commander, context=None, output=b\"\"):\n1615: +        scope = f\" ({context})\" if context else \"\"\n1616: +        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n1617: +            output + f\"fw{scope} #\".encode()\n1618: +        ))\n1619: +\n1620: +    @staticmethod\n1621: +    def writes(terminal):\n1622: +        return [call.args[0] for call in terminal.write.call_args_list]\n1623: +\n1624: +    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n1625: +        for close in (\"next\", \"end\"):\n1626: +            for capture in (False, True):\n1627: +                for best_effort in (False, True):\n1628: +                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n1629: +                        terminal = MagicMock()\n1630: +                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n1631: +                        feature = RecordingFeature(commander, \"commit\", [\n1632: +                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n1633: +                            \"set must-not-run 1\",\n1634: +                        ])\n1635: +                        feature.on_context_loss = MagicMock()\n1636: +                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n1637: +                        commander.start([feature, following])\n1638: +                        self.prompt(commander, \"port1\")\n1639: +                        # The failure code can span multiple serial reads.\n1640: +                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n1641: +                            data = Data(chunk)\n1642: +                            commander.on_output(data)\n1643: +                            self.assertTrue(data.discarded)\n1644: +                        if best_effort:\n1645: +                            self.prompt(commander, \"interface\")\n1646: +                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n1647: +                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n1648: +                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n1649: +                        else:\n1650: +                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n1651: +                                self.prompt(commander, \"interface\")\n1652: +                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n1653: +                        feature.on_context_loss.assert_not_called()\n1654: +                        self.assertEqual(feature.executed, [])\n1655: +                        self.assertFalse(feature.completed)\n1656: +\n1657: +    def test_closing_failure_with_same_prompt_still_ejects(self):\n1658: +        for code in (\"0\", \"7\", \"-61\"):\n1659: +            for suffix in (\"\", \".\"):\n1660: +                with self.subTest(code=code, suffix=suffix):\n1661: +                    terminal = MagicMock()\n1662: +                    commander = FOSCommander(terminal, MagicMock())\n1663: +                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n1664: +                    commander.start([feature])\n1665: +                    self.prompt(commander, \"port1\")\n1666: +                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n1667: +                        self.prompt(\n1668: +                            commander, \"port1\",\n1669: +                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n1670: +                        )\n1671: +                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n1672: +\n1673: +    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n1674: +        for capture in (False, True):\n1675: +            with self.subTest(capture=capture):\n1676: +                terminal = MagicMock()\n1677: +                commander = FOSCommander(terminal, MagicMock())\n1678: +                feature = RecordingFeature(commander, \"configure\", [\n1679: +                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1680: +                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n1681: +                    ])]),\n1682: +                ])\n1683: +                commander.start([feature])\n1684: +                self.prompt(commander)\n1685: +                self.prompt(commander, \"interface\")\n1686: +                self.prompt(commander, \"port1\")\n1687: +                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n1688: +                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n1689: +                self.prompt(commander, \"interface\")\n1690: +                self.prompt(commander)\n1691: +                self.assertTrue(feature.completed)\n1692: +                self.assertTrue(commander.ready)\n1693: +                self.assertEqual(commander.feature_errors, ())\n1694: +\n1695: +    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n1696: +        for best_effort in (False, True):\n1697: +            with self.subTest(best_effort=best_effort):\n1698: +                terminal = MagicMock()\n1699: +                commander = FOSCommander(terminal, MagicMock(), best_effort)\n1700: +                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n1701: +                following = RecordingFeature(commander, \"following\", [\"get status\"])\n1702: +                commander.register_cleanup(feature, CleanupAction(\n1703: +                    \"close\", CommandSequence(\"close\", [\"end\"]),\n1704: +                ))\n1705: +                commander.start([feature, following])\n1706: +                self.prompt(commander)\n1707: +                self.prompt(commander)\n1708: +                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n1709: +                if best_effort:\n1710: +                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n1711: +                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n1712: +                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n1713: +                else:\n1714: +                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n1715: +                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n1716: +                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n1717: +\n1718: +    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n1719: +        terminal = MagicMock()\n1720: +        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n1721: +        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n1722: +            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n1723: +            expected_completion_state=FOSCliState.CMD_PROMPT,\n1724: +        )])\n1725: +        commander.start([feature])\n1726: +        self.prompt(commander, \"interface\")\n1727: +        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n1728: +            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n1729: +        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n1730: +        self.assertFalse(feature.completed)\n1731: +\n1732: +\n1733: +if __name__ == \"__main__\":\n1734: +    unittest.main()\n1735: diff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\n1736: index 1e31693..d633771 100644\n1737: --- a/fortinet/tests/test_common_stack_boundaries.py\n1738: +++ b/fortinet/tests/test_common_stack_boundaries.py\n1739: @@ -38,15 +38,15 @@ class BoundaryFeature(Feature):\n1740:  \n1741:      def on_session_loss(self, attempt):\n1742:          return SessionLossAction.CONTINUE\n1743:  \n1744:  \n1745: -def make_stack(spec, response, *, allow_recovery=False):\n1746: +def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n1747:      logger = MagicMock()\n1748:      connection = SerialConnection({\n1749:          b\"admin\\r\": b\"Password:\",\n1750: -        b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1751: +        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n1752:          b\"probe\\r\": response,\n1753:      })\n1754:      terminal = Terminal(connection, logger, default_wait=\"fw #\")\n1755:      commander = FOSCommander(terminal, logger)\n1756:      feature = BoundaryFeature(commander, spec)\n1757: @@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):\n1758:      response = (\n1759:          (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n1760:          .encode()\n1761:      )\n1762:      spec = CommandSpec(\"probe\", capture_output=True)\n1763: -    connection, terminal, commander, driver, feature, states = make_stack(spec, response)\n1764: +    connection, terminal, commander, driver, feature, states = make_stack(\n1765: +        spec, response, initial_prompt=prompt.encode()\n1766: +    )\n1767:      try:\n1768:          with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n1769:                  patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1770:              driver.process_state()\n1771:          assert commander.ready\n1772: @@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b\"\", *, recover=False):\n1773:          completion = (state,)\n1774:      connection, terminal, commander, driver, feature, states = make_stack(\n1775:          CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n1776:          response,\n1777:          allow_recovery=recover,\n1778: +        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n1779:      )\n1780:      try:\n1781:          with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n1782:                  patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1783:              driver.process_state()\n1784: @@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):\n1785:              self.assertFalse(feature.completed)\n1786:              self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n1787:          finally:\n1788:              terminal.close()\n1789:  \n1790: -    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):\n1791: +    def test_idle_read_exposes_retained_prompt_newline(self):\n1792:          connection, terminal, commander, driver, feature, states = make_stack(\n1793:              CommandSpec(\"probe\", capture_output=True), None\n1794:          )\n1795:          try:\n1796:              with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n1797:                      patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n1798:                  driver.process_state()\n1799:              self.assertIn(FOSCliState.TN_TIMEOUT, states)\n1800: -            self.assertEqual(bytes(feature.current_attempt.output), b\"\")\n1801: +            # The login response ended with a newline after the matched CLI\n1802: +            # prompt. Full-buffer timeout inspection exposes that real byte.\n1803: +            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n1804:              self.assertTrue(commander.busy)\n1805:          finally:\n1806:              terminal.close()\n1807:  \n1808:      def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n1809:          command_echo = b\"fw (global) # probe\\r\\n\"\n1810:          payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n1811:          response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n1812:          connection, terminal, commander, driver, feature, states = make_stack(\n1813: -            CommandSpec(\"probe\", capture_output=True), response\n1814: +            CommandSpec(\"probe\", capture_output=True), response,\n1815: +            initial_prompt=b\"fw (global) #\",\n1816:          )\n1817:          try:\n1818:              with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n1819:                      patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n1820:                  driver.process_state()\n1821: diff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\n1822: index 74d6ef7..56346ea 100644\n1823: --- a/fortinet/tests/test_common_stack_parsing.py\n1824: +++ b/fortinet/tests/test_common_stack_parsing.py\n1825: @@ -7,11 +7,13 @@ from pathlib import Path\n1826:  from unittest.mock import MagicMock\n1827:  \n1828:  REPO_ROOT = Path(__file__).resolve().parents[2]\n1829:  sys.path.insert(0, str(REPO_ROOT))\n1830:  \n1831: -from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402\n1832: +from fortinet.common.cli_commands import (  # noqa: E402\n1833: +    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n1834: +)\n1835:  from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n1836:  from fortinet.common.features.base import Feature  # noqa: E402\n1837:  from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n1838:  from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n1839:  from fortinet.common.terminal import Terminal  # noqa: E402\n1840: @@ -35,10 +37,12 @@ class SerialConnection:\n1841:  \n1842:      def write(self, data):\n1843:          data = bytes(data)\n1844:          self.writes.append(data)\n1845:          response = self._responses.get(data)\n1846: +        if callable(response):\n1847: +            response = response()\n1848:          if response:\n1849:              chunks = response if isinstance(response, (tuple, list)) else (response,)\n1850:              for chunk in chunks:\n1851:                  if chunk:\n1852:                      self._incoming.put(bytes(chunk))\n1853: @@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):\n1854:          self.assertEqual(bytes(terminal._buffer), b\"\")\n1855:  \n1856:      def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n1857:          responses = {\n1858:              b\"admin\\r\": b\"Password:\",\n1859: -            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1860: +            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n1861:              b\"get system status\\r\": (\n1862:                  b\"fw (global) # get system status\\r\\n\"\n1863:                  b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n1864:                  b\"--More--\\r\\n\"\n1865:                  b\"Serial-Number: FGVMTEST\\r\\n\"\n1866: @@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):\n1867:          self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n1868:          self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n1869:          self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n1870:          self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n1871:  \n1872: +    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n1873: +        ip_responses = iter([\n1874: +            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n1875: +            b\"fw (port1) (Interim)#\\r\\n\",\n1876: +        ])\n1877: +        responses = {\n1878: +            b\"admin\\r\": b\"Password:\",\n1879: +            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n1880: +            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n1881: +            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n1882: +            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n1883: +            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n1884: +            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n1885: +            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n1886: +        }\n1887: +        feature_ref = []\n1888: +\n1889: +        def configured(commander):\n1890: +            feature = RecordingFeature(commander, \"management\", [\n1891: +                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n1892: +                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n1893: +                ])]),\n1894: +            ])\n1895: +            feature_ref.append(feature)\n1896: +            return [feature]\n1897: +\n1898: +        connection, terminal, commander, driver = self.make_stack(configured, responses)\n1899: +        try:\n1900: +            driver.process_state()\n1901: +            self.assertTrue(commander.ready)\n1902: +            self.assertTrue(feature_ref[0].completed)\n1903: +            self.assertEqual(connection.writes, [\n1904: +                b\"admin\\r\", b\"secret\\r\",\n1905: +                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n1906: +                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n1907: +                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n1908: +            ])\n1909: +        finally:\n1910: +            terminal.close()\n1911: +\n1912: +    def test_failed_next_ejects_before_end_through_serial_driver(self):\n1913: +        responses = {\n1914: +            b\"admin\\r\": b\"Password:\",\n1915: +            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n1916: +            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n1917: +            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n1918: +            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n1919: +            b\"next\\r\": (\n1920: +                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n1921: +            ),\n1922: +        }\n1923: +        feature_ref = []\n1924: +\n1925: +        def configured(commander):\n1926: +            feature = RecordingFeature(commander, \"management\", [\n1927: +                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n1928: +            ])\n1929: +            feature_ref.append(feature)\n1930: +            return [feature]\n1931: +\n1932: +        connection, terminal, commander, driver = self.make_stack(configured, responses)\n1933: +        try:\n1934: +            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n1935: +                driver.process_state()\n1936: +            self.assertEqual(connection.writes, [\n1937: +                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n1938: +                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n1939: +            ])\n1940: +            self.assertFalse(feature_ref[0].completed)\n1941: +            self.assertFalse(commander.ready)\n1942: +        finally:\n1943: +            terminal.close()\n1944: +\n1945:  \n1946:  if __name__ == \"__main__\":\n1947:      unittest.main()\n1948: diff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\n1949: index 4c0a37b..be7eab4 100644\n1950: --- a/fortinet/tests/test_common_terminal_driver.py\n1951: +++ b/fortinet/tests/test_common_terminal_driver.py\n1952: @@ -9,12 +9,16 @@ from contextlib import contextmanager\n1953:  from unittest.mock import MagicMock, patch\n1954:  \n1955:  REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n1956:  sys.path.insert(0, str(REPO_ROOT))\n1957:  \n1958: -from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n1959: -from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n1960: +from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n1961: +from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n1962: +from fortinet.common.fos_cli_driver import (  # noqa: E402\n1963: +    FOSCliDriver,\n1964: +    KernelPanicError,\n1965: +)\n1966:  from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n1967:  \n1968:  \n1969:  class ByteQueueTests(unittest.TestCase):\n1970:      def test_put_get_close_timeout_and_failure(self):\n1971: @@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):\n1972:          terminal._buffer_limit = 5\n1973:          with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n1974:              terminal._enforce_buffer_limit()\n1975:          terminal._logger.error.assert_called_once()\n1976:  \n1977: +    def test_timeout_preserves_partial_token_for_a_later_read(self):\n1978: +        terminal = self.terminal_with_data(b\"Login incor\")\n1979: +        pattern = rb\"(?m)^Login incorrect\\r?$\"\n1980: +        index, match, output = terminal.expect([pattern], timeout=0.001)\n1981: +        self.assertEqual((index, match), (-1, None))\n1982: +        self.assertEqual(bytes(output), b\"Login incor\")\n1983: +        # Inspection without discard keeps the partial token, including when\n1984: +        # another wait expires without receiving any more bytes.\n1985: +        _, _, output = terminal.expect([pattern], timeout=0)\n1986: +        self.assertEqual(bytes(output), b\"Login incor\")\n1987: +        terminal._read_queue.put(b\"rect\\n\")\n1988: +        index, match, output = terminal.expect([pattern], timeout=0.1)\n1989: +        self.assertEqual(index, 0)\n1990: +        self.assertEqual(match.group(), b\"Login incorrect\")\n1991: +        self.assertEqual(bytes(output), b\"Login incorrect\")\n1992: +        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n1993: +\n1994: +    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n1995: +        terminal = self.terminal_with_data(b\"Verifying pass\")\n1996: +        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n1997: +        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n1998: +\n1999: +        terminal._read_queue.put(b\"word...\\n\")\n2000: +        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n2001: +        self.assertIsNone(match)\n2002: +        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n2003: +        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n2004: +        output.discard()\n2005: +        self.assertEqual(bytes(terminal._buffer), b\"\")\n2006: +\n2007: +    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n2008: +        prefix = b\"\\nVerifying password...\\n\"\n2009: +        chunk = b\"admin\\nadmin\\n\"\n2010: +        terminal = self.terminal_with_data(chunk)\n2011: +        terminal._buffer.extend(prefix)\n2012: +\n2013: +        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n2014: +        self.assertEqual(bytes(output), prefix + chunk)\n2015: +        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n2016: +        attempt.on_output(output)\n2017: +\n2018: +        self.assertEqual(bytes(attempt.output), prefix + chunk)\n2019: +        self.assertEqual(bytes(terminal._buffer), b\"\")\n2020: +        terminal._logger.warning.assert_not_called()\n2021: +\n2022:      def test_suppression_is_nested_and_restores_context(self):\n2023:          @contextmanager\n2024:          def context():\n2025:              events.append(\"enter\")\n2026:              try:\n2027: @@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):\n2028:          with self.assertRaisesRegex(OSError, \"serial failed\"):\n2029:              queue.get(0)\n2030:          logger.exception.assert_called_once()\n2031:          with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n2032:              self.assertEqual(terminal_buffer_limit_bytes(), 32)\n2033: -        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n2034: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n2035: +            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n2036: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n2037:              with self.assertRaises(ValueError):\n2038:                  terminal_buffer_limit_bytes()\n2039:  \n2040: +    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n2041: +        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n2042: +            with self.subTest(env_name=env_name):\n2043: +                terminal = self.terminal_with_data(b\"matched\")\n2044: +                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n2045: +                    terminal.expect([b\"matched\"], timeout=0.1)\n2046: +                terminal._logger.log.assert_called_once_with(\n2047: +                    TRACE_LEVEL,\n2048: +                    \"buffer: bytearray(b'matched')\",\n2049: +                )\n2050: +\n2051:  \n2052:  class DriverTests(unittest.TestCase):\n2053:      def make_driver(self, *, allow_recovery=False):\n2054:          terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n2055:          commander.ready = False\n2056: @@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):\n2057:          self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n2058:          terminal.expect.return_value = (-1, None, Data(b\"\"))\n2059:          self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n2060:          driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n2061:  \n2062: +    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n2063: +        driver, _, _, logger, *_ = self.make_driver()\n2064: +        terminal = Terminal(MagicMock(), logger)\n2065: +        terminal._ensure_reader = lambda: None\n2066: +        terminal._read_queue.put(b\"partial token\")\n2067: +        driver._terminal = terminal\n2068: +\n2069: +        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n2070: +            state, output, matched = driver._next_state()\n2071: +            self.assertEqual(state, FOSCliState.UNKNOWN)\n2072: +            self.assertEqual(bytes(output), b\"partial token\")\n2073: +            self.assertFalse(matched)\n2074: +            state, output, matched = driver._next_state()\n2075: +            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n2076: +            self.assertEqual(bytes(output), b\"partial token\")\n2077: +            self.assertFalse(matched)\n2078: +\n2079: +    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n2080: +        driver, terminal, commander, *_ = self.make_driver()\n2081: +        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n2082: +        panic = (\n2083: +            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n2084: +            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n2085: +        )\n2086: +\n2087: +        self.assertIsNone(\n2088: +            re.search(\n2089: +                pattern,\n2090: +                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n2091: +            )\n2092: +        )\n2093: +        match = re.search(pattern, panic)\n2094: +        self.assertIsNotNone(match)\n2095: +        terminal.expect.return_value = (\n2096: +            FOSCliState.KERNEL_PANIC.value,\n2097: +            match,\n2098: +            Data(panic),\n2099: +        )\n2100: +\n2101: +        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n2102: +            driver.process_state()\n2103: +\n2104: +        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n2105: +\n2106:  \n2107:  if __name__ == \"__main__\":\n2108:      unittest.main()\n\n(End of file - total 2108 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+++ b/fortinet/tests/test_common_admin_credentials.py\n@@ -0,0 +1,154 @@\n+\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from types import SimpleNamespace\n+from unittest.mock import MagicMock, patch\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.common import Credentials\n+from fortinet.common.features.credentials import CredentialsFeature\n+from fortinet.common.fos_cli_driver import FOSCliDriver\n+from fortinet.common.fos_commander import FOSCommander\n+from fortinet.common.terminal import Terminal\n+from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n+\n+",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+++ b/fortinet/tests/test_common_admin_credentials.py\n@@ -0,0 +1,154 @@\n+\"\"\"Admin credential commits followed by logout and console authentication.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from types import SimpleNamespace\n+from unittest.mock import MagicMock, patch\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.common import Credentials\n+from fortinet.common.features.credentials import CredentialsFeature\n+from fortinet.common.fos_cli_driver import FOSCliDriver\n+from fortinet.common.fos_commander import FOSCommander\n+from fortinet.common.terminal import Terminal\n+from fortinet.tests.test_common_stack_parsing import RecordingFeature, SerialConnection\n+\n+\n+LOGIN = b\"fw login:\\r\\n\"\n+READY = b\"Welcome!\\r\\nfw #\\r\\n\"\n+ADMIN_PROMPT = b\"fw (admin) #\\r\\n\"\n+\n+\n+class AdminCredentialsTests(unittest.TestCase):\n+    def make_stack(self, *, password=\"newpass\", username=\"admin\",\n+                   auto_logout=None, authenticate=True, reject=False,\n+                   exit_works=True):\n+        logger = MagicMock()\n+        policy_prompt = b\"fw (password-policy) #\\r\\n\"\n+        old_password_responses = [READY]\n+        if password:\n+            old_password_responses.append(ADMIN_PROMPT)\n+        old_password_responses.append(b\"Login incorrect\\r\\n\" + LOGIN)\n+        end_count = 0\n+\n+        def end_response():\n+            nonlocal end_count\n+            end_count += 1\n+            return LOGIN if auto_logout == \"end\" and end_count == 2 else b\"fw #\\r\\n\"\n+\n+        login_reply = None if not authenticate else (\n+            b\"Login incorrect\\r\\n\" + LOGIN if reject else READY\n+        )\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"oldpass\\r\": lambda: old_password_responses.pop(0),\n+            b\"config system password-policy\\r\": policy_prompt,\n+            b\"set status disable\\r\": policy_prompt,\n+            b\"config system admin\\r\": ADMIN_PROMPT,\n+            f\"edit {username}\\r\".encode(): ADMIN_PROMPT,\n+            b\"set accprofile super_admin\\r\": ADMIN_PROMPT,\n+            b\"next\\r\": LOGIN if auto_logout == \"next\" else ADMIN_PROMPT,\n+            b\"end\\r\": end_response,\n+            b\"exit\\r\": LOGIN if exit_works else b\"fw #\\r\\n\",\n+            b\"probe\\r\": b\"fw #\\r\\n\",\n+            (password + \"\\r\").encode(): login_reply,\n+        }\n+        if username != \"admin\":\n+            responses[(username + \"\\r\").encode()] = b\"Password:\"\n+        if password:\n+            responses[f\"set password {password}\\r\".encode()] = (\n+                b\"Please enter current administrator password: \"\n+            )\n+        else:\n+            responses[b\"unset password\\r\"] = ADMIN_PROMPT\n+\n+        connection = SerialConnection(responses)\n+        terminal = Terminal(connection, logger)\n+        commander = FOSCommander(terminal, logger)\n+        credentials = Credentials(\"admin\", \"oldpass\")\n+        driver = FOSCliDriver(\n+            terminal, commander, credentials, logger, \"bootstrap\",\n+            MagicMock(), MagicMock(), allow_credential_recovery=True,\n+        )\n+\n+        def activate_desired():\n+            driver.remember_current_credentials()\n+            credentials.username = username\n+            credentials.password = password\n+\n+        vm = SimpleNamespace(\n+            desired_credentials=Credentials(username, password),\n+            activate_desired_credentials=activate_desired,\n+        )\n+        admin = CredentialsFeature(vm, commander)\n+        following = RecordingFeature(commander, \"following\", [\"probe\"])\n+        commander.start([admin, following])\n+        self.addCleanup(lambda: terminal.close() if not connection.closed else None)\n+        return connection, commander, driver, admin, following\n+\n+    def run_driver(self, driver):\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n+                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.15):\n+            driver.process_state()\n+\n+    def test_logout_and_relogin_after_committing_credentials(self):\n+        for username, password in ((\"admin\", \"newpass\"), (\"admin\", \"\"),\n+                                   (\"operator\", \"newpass\")):\n+            with self.subTest(username=username, password_set=bool(password)):\n+                conn, cmd, driver, admin, following = self.make_stack(\n+                    username=username, password=password,\n+                )\n+                self.run_driver(driver)\n+                self.assertTrue(cmd.ready)\n+                self.assertTrue(admin.completed)\n+                self.assertTrue(following.completed)\n+                logout = conn.writes.index(b\"exit\\r\")\n+                self.assertEqual(conn.writes[logout - 1], b\"end\\r\")\n+                self.assertEqual(conn.writes[logout + 1:], [\n+                    (username + \"\\r\").encode(),\n+                    (password + \"\\r\").encode(),\n+                    b\"probe\\r\",\n+                ])\n+                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n+\n+    def test_later_features_wait_for_authentication(self):\n+        conn, cmd, driver, admin, following = self.make_stack(authenticate=False)\n+        self.run_driver(driver)\n+        self.assertIn(b\"exit\\r\", conn.writes)\n+        self.assertIn(b\"newpass\\r\", conn.writes)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+        self.assertFalse(admin.completed)\n+        self.assertFalse(following.completed)\n+        self.assertFalse(cmd.ready)\n+\n+    def test_fortios_logout_at_commit_does_not_replay_password_change(self):\n+        for commit_command in (\"next\", \"end\"):\n+            with self.subTest(commit_command=commit_command):\n+                conn, cmd, driver, admin, _ = self.make_stack(auto_logout=commit_command)\n+                self.run_driver(driver)\n+                self.assertTrue(cmd.ready)\n+                self.assertTrue(admin.completed)\n+                self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n+                self.assertEqual(conn.writes.count(b\"exit\\r\"), 1)\n+                self.assertEqual(conn.writes.count(b\"newpass\\r\"), 2)\n+\n+    def test_logout_must_return_to_login(self):\n+        conn, _, driver, admin, _ = self.make_stack(exit_works=False)\n+        with self.assertRaisesRegex(RuntimeError, \"expected PROVIDE_USERNAME\"):\n+            self.run_driver(driver)\n+        self.assertFalse(admin.completed)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+\n+    def test_rejected_credentials_do_not_start_later_features(self):\n+        conn, _, driver, admin, _ = self.make_stack(reject=True)\n+        with self.assertRaisesRegex(RuntimeError, \"Credential rejected\"):\n+            self.run_driver(driver)\n+        self.assertFalse(admin.completed)\n+        self.assertNotIn(b\"probe\\r\", conn.writes)\n+        self.assertEqual(conn.writes.count(b\"set password newpass\\r\"), 1)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_recovery.py b/fortinet/tests/test_common_recovery.py\nnew file mode 100644\nindex 0000000..2afb43a\n--- /dev/null\n+++ b/fortinet/tests/test_common_recovery.py\n@@ -0,0 +1,292 @@\n+\"\"\"Bounded recovery after a scope exit or an interrupted CLI session.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, ContextLossAction,\n+    EditBlock, SessionLossAction,\n+)\n+from fortinet.common.common import FOSCliState  # noqa: E402\n+from fortinet.common.features.base import Feature, StaticFeature  # noqa: E402\n+from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n+from fortinet.common.terminal import Data  # noqa: E402\n+\n+\n+IP_COMMAND = \"set ip 10.0.52.4/24\"\n+ACCESS_COMMAND = \"set allowaccess ping https ssh http\"\n+\n+\n+class RecordingFeature(Feature):\n+    def __init__(self, commander, block, context_action=None):\n+        super().__init__(None, commander, \"management\")\n+        self.block = block\n+        self.context_action = context_action\n+        self.losses = []\n+        self.attempts = []\n+        self.executed = []\n+\n+    def activate(self):\n+        self.commander.submit_block(self, self.block)\n+\n+    def on_command_dispatched(self, attempt):\n+        super().on_command_dispatched(attempt)\n+        self.attempts.append(attempt)\n+\n+    def on_command_executed(self, attempt, state):\n+        self.executed.append(attempt.spec.line)\n+\n+    def on_context_loss(self, attempt):\n+        self.losses.append(attempt)\n+        if self.context_action is not None:\n+            return self.context_action\n+        return super().on_context_loss(attempt)\n+\n+\n+class RecoveryTests(unittest.TestCase):\n+    def make_commander(self, *, continue_on_error=False, ip_command=IP_COMMAND,\n+                       context_action=None, following=False):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock(), continue_on_error)\n+        block = ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+            ip_command, ACCESS_COMMAND,\n+        ])])\n+        feature = RecordingFeature(commander, block, context_action)\n+        features = [feature]\n+        if following:\n+            features.append(RecordingFeature(\n+                commander, CommandSequence(\"following\", [\"get system status\"])\n+            ))\n+        commander.start(features)\n+        return commander, terminal, feature\n+\n+    def prompt(self, commander, context=None):\n+        scope = f\" ({context})\" if context else \"\"\n+        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n+            f\"FGT-VM64-KVM-NSVHDM{scope} (Interim)#\".encode()\n+        ))\n+\n+    def enter_interface(self, commander):\n+        self.prompt(commander, \"interface\")\n+        self.prompt(commander, \"port1\")\n+\n+    def finish_interface(self, commander):\n+        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n+        self.prompt(commander, \"port1\")  # allowaccess succeeds; dispatch next.\n+        self.prompt(commander, \"interface\")  # next succeeds; dispatch end.\n+        self.prompt(commander)  # end succeeds.\n+\n+    @staticmethod\n+    def writes(terminal):\n+        return [call.args[0] for call in terminal.write.call_args_list]\n+\n+    def reconnect(self, commander):\n+        commander.on_state(FOSCliState.CREDENTIAL_ACCEPTED, Data(b\"Welcome!\"))\n+        self.prompt(commander)\n+\n+    def test_scope_exit_replays_openers_before_retrying_the_failed_command(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)  # set ip unexpectedly returns to the VDOM shell.\n+        self.assertEqual(self.writes(terminal), [\n+            \"config system interface\\r\", \"edit port1\\r\", IP_COMMAND + \"\\r\",\n+            \"config system interface\\r\",\n+        ])\n+        self.assertNotIn(IP_COMMAND, feature.executed)\n+        self.assertEqual(feature.losses[0].prompt_context_before, (\"port1\", \"Interim\"))\n+        self.assertEqual(feature.losses[0].prompt_context_after, (\"Interim\",))\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        ip_attempts = [item for item in feature.attempts if item.spec.line == IP_COMMAND]\n+        self.assertEqual([item.retry_count for item in ip_attempts], [0, 1])\n+        self.assertTrue(feature.completed)\n+        self.assertTrue(commander.ready)\n+\n+    def test_repeated_context_loss_obeys_retry_limit_and_bootstrap_error_policy(self):\n+        for best_effort in (False, True):\n+            with self.subTest(best_effort=best_effort):\n+                commander, terminal, feature = self.make_commander(\n+                    continue_on_error=best_effort, following=True,\n+                )\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                if best_effort:\n+                    self.prompt(commander)\n+                    self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+                    self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+                else:\n+                    with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+                        self.prompt(commander)\n+                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n+                self.assertNotIn(ACCESS_COMMAND + \"\\r\", self.writes(terminal))\n+                self.assertFalse(feature.completed)\n+\n+    def test_session_and_context_loss_share_the_same_command_retry_allowance(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+            self.prompt(commander)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 2)\n+        self.assertEqual(feature.losses[0].retry_count, 1)\n+\n+    def test_repeated_session_loss_waits_for_login_before_best_effort_skip(self):\n+        commander, terminal, _feature = self.make_commander(\n+            continue_on_error=True, following=True,\n+        )\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n+        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n+        self.reconnect(commander)\n+        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+\n+    def test_login_without_welcome_resumes_replay_and_exhaustion_handling(self):\n+        commander, terminal, _feature = self.make_commander(\n+            continue_on_error=True, following=True,\n+        )\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.prompt(commander)  # Successful login returns a prompt, no Welcome.\n+        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n+        self.enter_interface(commander)\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost again\"))\n+        self.assertNotIn(\"get system status\\r\", self.writes(terminal))\n+        self.prompt(commander)  # Exhaustion is handled at this usable prompt.\n+        self.assertEqual(self.writes(terminal)[-1], \"get system status\\r\")\n+        self.assertIn(\"retry limit\", commander.feature_errors[0][1])\n+\n+    def test_each_command_position_gets_one_recovery(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)  # First loss: IP command.\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"port1\")  # IP succeeds; dispatch allowaccess.\n+        self.prompt(commander)  # Second loss: allowaccess command.\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 3)\n+        self.assertEqual(self.writes(terminal).count(ACCESS_COMMAND + \"\\r\"), 2)\n+\n+    def test_feature_can_decline_replay_without_running_session_loss_callback(self):\n+        for explicit_policy in (False, True):\n+            with self.subTest(explicit_policy=explicit_policy):\n+                spec = CommandSpec(IP_COMMAND, session_loss=SessionLossAction.CONTINUE)\n+                commander, terminal, feature = self.make_commander(\n+                    ip_command=IP_COMMAND if explicit_policy else spec,\n+                    context_action=ContextLossAction.FAIL if explicit_policy else None,\n+                )\n+                feature.on_session_loss = MagicMock()\n+                self.prompt(commander)\n+                self.enter_interface(commander)\n+                with self.assertRaisesRegex(RuntimeError, \"feature declined replay\"):\n+                    self.prompt(commander)\n+                feature.on_session_loss.assert_not_called()\n+                self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n+\n+    def test_explicit_context_policy_can_allow_replay_independently_of_logout_policy(self):\n+        spec = CommandSpec(\n+            IP_COMMAND, session_loss=SessionLossAction.CONTINUE,\n+            context_loss=ContextLossAction.RESTART_BLOCK,\n+        )\n+        commander, _terminal, feature = self.make_commander(ip_command=spec)\n+        feature.on_session_loss = MagicMock()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        feature.on_session_loss.assert_not_called()\n+\n+    def test_partial_scope_is_aborted_once_before_replay(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")  # Only the edit context disappeared.\n+        self.assertEqual(self.writes(terminal)[-1], \"abort\\r\")\n+        self.prompt(commander)\n+        self.assertEqual(self.writes(terminal)[-1], \"config system interface\\r\")\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertNotIn(\"abort\", feature.executed)\n+        self.assertNotIn(\"abort\", [item.spec.line for item in feature.attempts])\n+\n+    def test_failed_context_reset_does_not_loop(self):\n+        commander, terminal, _feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")\n+        with self.assertRaisesRegex(RuntimeError, \"Unable to restore CLI context\"):\n+            self.prompt(commander, \"interface\")\n+        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n+        self.assertEqual(self.writes(terminal).count(IP_COMMAND + \"\\r\"), 1)\n+\n+    def test_session_loss_during_context_reset_resumes_after_login(self):\n+        commander, terminal, feature = self.make_commander()\n+        self.prompt(commander)\n+        self.enter_interface(commander)\n+        self.prompt(commander, \"interface\")\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        self.enter_interface(commander)\n+        self.finish_interface(commander)\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(\"abort\\r\"), 1)\n+\n+    def test_cleanup_session_loss_is_bounded(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock())\n+        feature = RecordingFeature(commander, CommandSequence(\"work\", [\"get status\"]))\n+        commander.register_cleanup(feature, CleanupAction(\n+            \"cleanup\", CommandSequence(\"cleanup\", [\"get cleanup\"]),\n+        ))\n+        commander.start([feature])\n+        self.prompt(commander)\n+        self.prompt(commander)  # Begin cleanup after the feature completes.\n+        commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.reconnect(commander)\n+        with self.assertRaisesRegex(RuntimeError, \"retry limit\"):\n+            commander.on_state(FOSCliState.SESSION_LOST, Data(b\"session lost\"))\n+        self.assertEqual(self.writes(terminal).count(\"get cleanup\\r\"), 2)\n+\n+    def test_newly_submitted_block_resets_retry_allowance(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock())\n+        feature = StaticFeature(None, commander, \"two-blocks\", [\n+            ConfigBlock(\"system global\", [\"set alias first\"]),\n+            ConfigBlock(\"system global\", [\"set alias second\"]),\n+        ])\n+        commander.start([feature])\n+        self.prompt(commander)\n+        for _index in range(2):\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander)  # Lost context: retry this block.\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander, \"global\")\n+            self.prompt(commander)  # End this block and start the next one.\n+        self.assertTrue(feature.completed)\n+        self.assertEqual(self.writes(terminal).count(\"set alias first\\r\"), 2)\n+        self.assertEqual(self.writes(terminal).count(\"set alias second\\r\"), 2)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_scope_errors.py b/fortinet/tests/test_common_scope_errors.py\nnew file mode 100644\nindex 0000000..56ce729\n--- /dev/null\n+++ b/fortinet/tests/test_common_scope_errors.py\n@@ -0,0 +1,154 @@\n+\"\"\"Scope commit failures are mandatory errors, including best-effort commands.\"\"\"\n+\n+import sys\n+import unittest\n+from pathlib import Path\n+from unittest.mock import MagicMock\n+\n+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))\n+\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CleanupAction, CommandSequence, CommandSpec, ConfigBlock, EditBlock,\n+)\n+from fortinet.common.common import FOSCliState  # noqa: E402\n+from fortinet.common.features.base import Feature  # noqa: E402\n+from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n+from fortinet.common.terminal import Data  # noqa: E402\n+\n+\n+class RecordingFeature(Feature):\n+    def __init__(self, commander, name, commands):\n+        super().__init__(None, commander, name)\n+        self.commands = commands\n+        self.executed = []\n+\n+    def activate(self):\n+        self.commander.submit_block(self, CommandSequence(self.name, self.commands))\n+\n+    def on_command_executed(self, attempt, state):\n+        self.executed.append(attempt.spec.line)\n+\n+\n+class ScopeCommitFailureTests(unittest.TestCase):\n+    @staticmethod\n+    def prompt(commander, context=None, output=b\"\"):\n+        scope = f\" ({context})\" if context else \"\"\n+        commander.on_state(FOSCliState.CMD_PROMPT, Data(\n+            output + f\"fw{scope} #\".encode()\n+        ))\n+\n+    @staticmethod\n+    def writes(terminal):\n+        return [call.args[0] for call in terminal.write.call_args_list]\n+\n+    def test_closing_failure_cannot_be_disabled_or_replayed(self):\n+        for close in (\"next\", \"end\"):\n+            for capture in (False, True):\n+                for best_effort in (False, True):\n+                    with self.subTest(close=close, capture=capture, best_effort=best_effort):\n+                        terminal = MagicMock()\n+                        commander = FOSCommander(terminal, MagicMock(), best_effort)\n+                        feature = RecordingFeature(commander, \"commit\", [\n+                            CommandSpec(close, capture_output=capture, fail_on_error=False),\n+                            \"set must-not-run 1\",\n+                        ])\n+                        feature.on_context_loss = MagicMock()\n+                        following = RecordingFeature(commander, \"following\", [\"get status\"])\n+                        commander.start([feature, following])\n+                        self.prompt(commander, \"port1\")\n+                        # The failure code can span multiple serial reads.\n+                        for chunk in (b\"Command fa\", b\"il. Return co\", b\"de -542.\\r\\n\"):\n+                            data = Data(chunk)\n+                            commander.on_output(data)\n+                            self.assertTrue(data.discarded)\n+                        if best_effort:\n+                            self.prompt(commander, \"interface\")\n+                            self.assertEqual(self.writes(terminal), [close + \"\\r\", \"get status\\r\"])\n+                            self.assertEqual(commander.feature_errors[0][0], \"commit\")\n+                            self.assertIn(\"return code -542\", commander.feature_errors[0][1])\n+                        else:\n+                            with self.assertRaisesRegex(RuntimeError, \"return code -542\"):\n+                                self.prompt(commander, \"interface\")\n+                            self.assertEqual(self.writes(terminal), [close + \"\\r\"])\n+                        feature.on_context_loss.assert_not_called()\n+                        self.assertEqual(feature.executed, [])\n+                        self.assertFalse(feature.completed)\n+\n+    def test_closing_failure_with_same_prompt_still_ejects(self):\n+        for code in (\"0\", \"7\", \"-61\"):\n+            for suffix in (\"\", \".\"):\n+                with self.subTest(code=code, suffix=suffix):\n+                    terminal = MagicMock()\n+                    commander = FOSCommander(terminal, MagicMock())\n+                    feature = RecordingFeature(commander, \"commit\", [\"next\", \"end\"])\n+                    commander.start([feature])\n+                    self.prompt(commander, \"port1\")\n+                    with self.assertRaisesRegex(RuntimeError, f\"return code {code}\"):\n+                        self.prompt(\n+                            commander, \"port1\",\n+                            f\"  Command fail. Return code {code}{suffix}\\r\\n\".encode(),\n+                        )\n+                    self.assertEqual(self.writes(terminal), [\"next\\r\"])\n+\n+    def test_tolerated_set_failure_does_not_poison_successful_scope_close(self):\n+        for capture in (False, True):\n+            with self.subTest(capture=capture):\n+                terminal = MagicMock()\n+                commander = FOSCommander(terminal, MagicMock())\n+                feature = RecordingFeature(commander, \"configure\", [\n+                    ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+                        CommandSpec(\"set unsupported 1\", capture_output=capture),\n+                    ])]),\n+                ])\n+                commander.start([feature])\n+                self.prompt(commander)\n+                self.prompt(commander, \"interface\")\n+                self.prompt(commander, \"port1\")\n+                self.prompt(commander, \"port1\", b\"Command fail. Return code -61.\\r\\n\")\n+                self.assertEqual(self.writes(terminal)[-1], \"next\\r\")\n+                self.prompt(commander, \"interface\")\n+                self.prompt(commander)\n+                self.assertTrue(feature.completed)\n+                self.assertTrue(commander.ready)\n+                self.assertEqual(commander.feature_errors, ())\n+\n+    def test_cleanup_closing_failure_uses_bootstrap_error_policy(self):\n+        for best_effort in (False, True):\n+            with self.subTest(best_effort=best_effort):\n+                terminal = MagicMock()\n+                commander = FOSCommander(terminal, MagicMock(), best_effort)\n+                feature = RecordingFeature(commander, \"work\", [\"get initial\"])\n+                following = RecordingFeature(commander, \"following\", [\"get status\"])\n+                commander.register_cleanup(feature, CleanupAction(\n+                    \"close\", CommandSequence(\"close\", [\"end\"]),\n+                ))\n+                commander.start([feature, following])\n+                self.prompt(commander)\n+                self.prompt(commander)\n+                self.assertEqual(self.writes(terminal)[-1], \"end\\r\")\n+                if best_effort:\n+                    self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n+                    self.assertEqual(commander.feature_errors[0][0], \"cleanup\")\n+                    self.assertEqual(self.writes(terminal)[-1], \"get status\\r\")\n+                else:\n+                    with self.assertRaisesRegex(RuntimeError, \"return code -5\"):\n+                        self.prompt(commander, output=b\"Command fail. Return code -5.\\r\\n\")\n+                    self.assertNotIn(\"get status\\r\", self.writes(terminal))\n+\n+    def test_unusable_completion_prompt_cannot_enter_best_effort_wait(self):\n+        terminal = MagicMock()\n+        commander = FOSCommander(terminal, MagicMock(), continue_on_error=True)\n+        feature = RecordingFeature(commander, \"commit\", [CommandSpec(\n+            \"end\", completion_states=(FOSCliState.CONFIRMATION,),\n+            expected_completion_state=FOSCliState.CMD_PROMPT,\n+        )])\n+        commander.start([feature])\n+        self.prompt(commander, \"interface\")\n+        with self.assertRaisesRegex(RuntimeError, \"unexpected prompt\"):\n+            commander.on_state(FOSCliState.CONFIRMATION, Data(b\"Do you want to continue?\"))\n+        self.assertEqual(self.writes(terminal), [\"end\\r\"])\n+        self.assertFalse(feature.completed)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/fortinet/tests/test_common_stack_boundaries.py b/fortinet/tests/test_common_stack_boundaries.py\nindex 1e31693..d633771 100644\n--- a/fortinet/tests/test_common_stack_boundaries.py\n+++ b/fortinet/tests/test_common_stack_boundaries.py\n@@ -38,15 +38,15 @@ class BoundaryFeature(Feature):\n \n     def on_session_loss(self, attempt):\n         return SessionLossAction.CONTINUE\n \n \n-def make_stack(spec, response, *, allow_recovery=False):\n+def make_stack(spec, response, *, allow_recovery=False, initial_prompt=b\"fw #\"):\n     logger = MagicMock()\n     connection = SerialConnection({\n         b\"admin\\r\": b\"Password:\",\n-        b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+        b\"secret\\r\": b\"Welcome!\\r\\n\" + initial_prompt + b\"\\r\\n\",\n         b\"probe\\r\": response,\n     })\n     terminal = Terminal(connection, logger, default_wait=\"fw #\")\n     commander = FOSCommander(terminal, logger)\n     feature = BoundaryFeature(commander, spec)\n@@ -81,11 +81,13 @@ def prompt_case(hostname, context, marker, ending):\n     response = (\n         (prompt + \" probe\" + ending + \"captured diagnostic\" + ending + prompt + ending)\n         .encode()\n     )\n     spec = CommandSpec(\"probe\", capture_output=True)\n-    connection, terminal, commander, driver, feature, states = make_stack(spec, response)\n+    connection, terminal, commander, driver, feature, states = make_stack(\n+        spec, response, initial_prompt=prompt.encode()\n+    )\n     try:\n         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n             driver.process_state()\n         assert commander.ready\n@@ -108,10 +110,11 @@ def state_case(state, sample, suffix=b\"\", *, recover=False):\n         completion = (state,)\n     connection, terminal, commander, driver, feature, states = make_stack(\n         CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n         response,\n         allow_recovery=recover,\n+        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n     )\n     try:\n         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n             driver.process_state()\n@@ -172,30 +175,33 @@ class EndToEndBoundaryCases(unittest.TestCase):\n             self.assertFalse(feature.completed)\n             self.assertIn(b\"garbage\", bytes(feature.current_attempt.output))\n         finally:\n             terminal.close()\n \n-    def test_empty_connection_read_reaches_timeout_without_fabricating_output(self):\n+    def test_idle_read_exposes_retained_prompt_newline(self):\n         connection, terminal, commander, driver, feature, states = make_stack(\n             CommandSpec(\"probe\", capture_output=True), None\n         )\n         try:\n             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.01), \\\n                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 0.04):\n                 driver.process_state()\n             self.assertIn(FOSCliState.TN_TIMEOUT, states)\n-            self.assertEqual(bytes(feature.current_attempt.output), b\"\")\n+            # The login response ended with a newline after the matched CLI\n+            # prompt. Full-buffer timeout inspection exposes that real byte.\n+            self.assertEqual(bytes(feature.current_attempt.output), b\"\\n\")\n             self.assertTrue(commander.busy)\n         finally:\n             terminal.close()\n \n     def test_partial_prompt_and_command_echo_are_buffered_across_reads(self):\n         command_echo = b\"fw (global) # probe\\r\\n\"\n         payload = b\"config system dns\\r\\n set primary 1.1.1.1\\r\\nend\\r\\nfw (global) #\\r\\n\"\n         response = tuple([command_echo[:3], command_echo[3:12], command_echo[12:] + payload[:11], payload[11:29], payload[29:]])\n         connection, terminal, commander, driver, feature, states = make_stack(\n-            CommandSpec(\"probe\", capture_output=True), response\n+            CommandSpec(\"probe\", capture_output=True), response,\n+            initial_prompt=b\"fw (global) #\",\n         )\n         try:\n             with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                     patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n                 driver.process_state()\ndiff --git a/fortinet/tests/test_common_stack_parsing.py b/fortinet/tests/test_common_stack_parsing.py\nindex 74d6ef7..56346ea 100644\n--- a/fortinet/tests/test_common_stack_parsing.py\n+++ b/fortinet/tests/test_common_stack_parsing.py\n@@ -7,11 +7,13 @@ from pathlib import Path\n from unittest.mock import MagicMock\n \n REPO_ROOT = Path(__file__).resolve().parents[2]\n sys.path.insert(0, str(REPO_ROOT))\n \n-from fortinet.common.cli_commands import CommandSequence, CommandSpec, SetValue  # noqa: E402\n+from fortinet.common.cli_commands import (  # noqa: E402\n+    CommandSequence, CommandSpec, ConfigBlock, EditBlock, SetValue,\n+)\n from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n from fortinet.common.features.base import Feature  # noqa: E402\n from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n from fortinet.common.fos_commander import FOSCommander  # noqa: E402\n from fortinet.common.terminal import Terminal  # noqa: E402\n@@ -35,10 +37,12 @@ class SerialConnection:\n \n     def write(self, data):\n         data = bytes(data)\n         self.writes.append(data)\n         response = self._responses.get(data)\n+        if callable(response):\n+            response = response()\n         if response:\n             chunks = response if isinstance(response, (tuple, list)) else (response,)\n             for chunk in chunks:\n                 if chunk:\n                     self._incoming.put(bytes(chunk))\n@@ -145,11 +149,11 @@ class FullStackParsingTests(unittest.TestCase):\n         self.assertEqual(bytes(terminal._buffer), b\"\")\n \n     def test_mixed_prompt_context_and_pager_states_reach_feature_callbacks(self):\n         responses = {\n             b\"admin\\r\": b\"Password:\",\n-            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw (global) #\\r\\n\",\n             b\"get system status\\r\": (\n                 b\"fw (global) # get system status\\r\\n\"\n                 b\"Version: FortiGate-VM64 v7.4.2,build2571\\r\\n\"\n                 b\"--More--\\r\\n\"\n                 b\"Serial-Number: FGVMTEST\\r\\n\"\n@@ -184,8 +188,81 @@ class FullStackParsingTests(unittest.TestCase):\n         self.assertIn(b\"FortiGate-VM64 v7.4.2,build2571\", captured)\n         self.assertIn(b\"Serial-Number: FGVMTEST\", captured)\n         self.assertEqual(feature.executed[0][2], FOSCliState.CMD_PROMPT)\n         self.assertEqual(driver._current_state, FOSCliState.CMD_PROMPT)\n \n+    def test_aborted_interface_edit_recovers_through_serial_driver(self):\n+        ip_responses = iter([\n+            b\"abort\\r\\nfw (Interim)#\\r\\n\",\n+            b\"fw (port1) (Interim)#\\r\\n\",\n+        ])\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw (Interim)#\\r\\n\",\n+            b\"config system interface\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n+            b\"edit port1\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n+            b\"set ip 10.0.52.4/24\\r\": lambda: next(ip_responses),\n+            b\"set allowaccess ping https ssh http\\r\": b\"fw (port1) (Interim)#\\r\\n\",\n+            b\"next\\r\": b\"fw (interface) (Interim)#\\r\\n\",\n+            b\"end\\r\": b\"fw (Interim)#\\r\\n\",\n+        }\n+        feature_ref = []\n+\n+        def configured(commander):\n+            feature = RecordingFeature(commander, \"management\", [\n+                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\n+                    \"set ip 10.0.52.4/24\", \"set allowaccess ping https ssh http\",\n+                ])]),\n+            ])\n+            feature_ref.append(feature)\n+            return [feature]\n+\n+        connection, terminal, commander, driver = self.make_stack(configured, responses)\n+        try:\n+            driver.process_state()\n+            self.assertTrue(commander.ready)\n+            self.assertTrue(feature_ref[0].completed)\n+            self.assertEqual(connection.writes, [\n+                b\"admin\\r\", b\"secret\\r\",\n+                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n+                b\"config system interface\\r\", b\"edit port1\\r\", b\"set ip 10.0.52.4/24\\r\",\n+                b\"set allowaccess ping https ssh http\\r\", b\"next\\r\", b\"end\\r\",\n+            ])\n+        finally:\n+            terminal.close()\n+\n+    def test_failed_next_ejects_before_end_through_serial_driver(self):\n+        responses = {\n+            b\"admin\\r\": b\"Password:\",\n+            b\"secret\\r\": b\"Welcome!\\r\\nfw #\\r\\n\",\n+            b\"config system interface\\r\": b\"fw (interface)#\\r\\n\",\n+            b\"edit port1\\r\": b\"fw (port1)#\\r\\n\",\n+            b\"set unsupported 1\\r\": b\"Command fail. Return code -61.\\r\\nfw (port1)#\\r\\n\",\n+            b\"next\\r\": (\n+                b\"Command fa\", b\"il. Return code -5.\\r\\nfw (port1)#\\r\\n\",\n+            ),\n+        }\n+        feature_ref = []\n+\n+        def configured(commander):\n+            feature = RecordingFeature(commander, \"management\", [\n+                ConfigBlock(\"system interface\", [EditBlock(\"port1\", [\"set unsupported 1\"])]),\n+            ])\n+            feature_ref.append(feature)\n+            return [feature]\n+\n+        connection, terminal, commander, driver = self.make_stack(configured, responses)\n+        try:\n+            with self.assertRaisesRegex(RuntimeError, \"'next'.*return code -5\"):\n+                driver.process_state()\n+            self.assertEqual(connection.writes, [\n+                b\"admin\\r\", b\"secret\\r\", b\"config system interface\\r\",\n+                b\"edit port1\\r\", b\"set unsupported 1\\r\", b\"next\\r\",\n+            ])\n+            self.assertFalse(feature_ref[0].completed)\n+            self.assertFalse(commander.ready)\n+        finally:\n+            terminal.close()\n+\n \n if __name__ == \"__main__\":\n     unittest.main()\ndiff --git a/fortinet/tests/test_common_terminal_driver.py b/fortinet/tests/test_common_terminal_driver.py\nindex 4c0a37b..be7eab4 100644\n--- a/fortinet/tests/test_common_terminal_driver.py\n+++ b/fortinet/tests/test_common_terminal_driver.py\n@@ -9,12 +9,16 @@ from contextlib import contextmanager\n from unittest.mock import MagicMock, patch\n \n REPO_ROOT = __import__(\"pathlib\").Path(__file__).resolve().parents[2]\n sys.path.insert(0, str(REPO_ROOT))\n \n-from fortinet.common.common import Credentials, FOSCliState  # noqa: E402\n-from fortinet.common.fos_cli_driver import FOSCliDriver  # noqa: E402\n+from fortinet.common.cli_commands import CommandAttempt, CommandSpec  # noqa: E402\n+from fortinet.common.common import Credentials, FOSCliState, TRACE_LEVEL  # noqa: E402\n+from fortinet.common.fos_cli_driver import (  # noqa: E402\n+    FOSCliDriver,\n+    KernelPanicError,\n+)\n from fortinet.common.terminal import Data, Terminal, _ByteQueue, terminal_buffer_limit_bytes  # noqa: E402\n \n \n class ByteQueueTests(unittest.TestCase):\n     def test_put_get_close_timeout_and_failure(self):\n@@ -83,10 +87,55 @@ class TerminalTests(unittest.TestCase):\n         terminal._buffer_limit = 5\n         with self.assertRaisesRegex(RuntimeError, \"exceeded 5\"):\n             terminal._enforce_buffer_limit()\n         terminal._logger.error.assert_called_once()\n \n+    def test_timeout_preserves_partial_token_for_a_later_read(self):\n+        terminal = self.terminal_with_data(b\"Login incor\")\n+        pattern = rb\"(?m)^Login incorrect\\r?$\"\n+        index, match, output = terminal.expect([pattern], timeout=0.001)\n+        self.assertEqual((index, match), (-1, None))\n+        self.assertEqual(bytes(output), b\"Login incor\")\n+        # Inspection without discard keeps the partial token, including when\n+        # another wait expires without receiving any more bytes.\n+        _, _, output = terminal.expect([pattern], timeout=0)\n+        self.assertEqual(bytes(output), b\"Login incor\")\n+        terminal._read_queue.put(b\"rect\\n\")\n+        index, match, output = terminal.expect([pattern], timeout=0.1)\n+        self.assertEqual(index, 0)\n+        self.assertEqual(match.group(), b\"Login incorrect\")\n+        self.assertEqual(bytes(output), b\"Login incorrect\")\n+        self.assertEqual(bytes(terminal._buffer), b\"\\n\")\n+\n+    def test_timeout_inspection_sees_a_token_completed_by_new_input(self):\n+        terminal = self.terminal_with_data(b\"Verifying pass\")\n+        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertIsNone(re.search(rb\"Verifying password\", bytes(output)))\n+\n+        terminal._read_queue.put(b\"word...\\n\")\n+        _, match, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertIsNone(match)\n+        self.assertIsNotNone(re.search(rb\"Verifying password\", bytes(output)))\n+        self.assertEqual(bytes(terminal._buffer), b\"Verifying password...\\n\")\n+        output.discard()\n+        self.assertEqual(bytes(terminal._buffer), b\"\")\n+\n+    def test_timeout_capture_consumes_retained_prefix_and_new_bytes(self):\n+        prefix = b\"\\nVerifying password...\\n\"\n+        chunk = b\"admin\\nadmin\\n\"\n+        terminal = self.terminal_with_data(chunk)\n+        terminal._buffer.extend(prefix)\n+\n+        _, _, output = terminal.expect([b\"fw #\"], timeout=0.001)\n+        self.assertEqual(bytes(output), prefix + chunk)\n+        attempt = CommandAttempt(CommandSpec(\"end\"), 1, 0)\n+        attempt.on_output(output)\n+\n+        self.assertEqual(bytes(attempt.output), prefix + chunk)\n+        self.assertEqual(bytes(terminal._buffer), b\"\")\n+        terminal._logger.warning.assert_not_called()\n+\n     def test_suppression_is_nested_and_restores_context(self):\n         @contextmanager\n         def context():\n             events.append(\"enter\")\n             try:\n@@ -124,14 +173,27 @@ class TerminalTests(unittest.TestCase):\n         with self.assertRaisesRegex(OSError, \"serial failed\"):\n             queue.get(0)\n         logger.exception.assert_called_once()\n         with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n             self.assertEqual(terminal_buffer_limit_bytes(), 32)\n-        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n+        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n+            self.assertEqual(terminal_buffer_limit_bytes(), 64)\n+        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n             with self.assertRaises(ValueError):\n                 terminal_buffer_limit_bytes()\n \n+    def test_raw_serial_log_uses_ftnt_name_and_legacy_fos_alias(self):\n+        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n+            with self.subTest(env_name=env_name):\n+                terminal = self.terminal_with_data(b\"matched\")\n+                with patch.dict(\"os.environ\", {env_name: \"true\"}, clear=True):\n+                    terminal.expect([b\"matched\"], timeout=0.1)\n+                terminal._logger.log.assert_called_once_with(\n+                    TRACE_LEVEL,\n+                    \"buffer: bytearray(b'matched')\",\n+                )\n+\n \n class DriverTests(unittest.TestCase):\n     def make_driver(self, *, allow_recovery=False):\n         terminal, commander, logger = MagicMock(), MagicMock(), MagicMock()\n         commander.ready = False\n@@ -219,8 +281,52 @@ class DriverTests(unittest.TestCase):\n         self.assertEqual(driver._next_state()[0], FOSCliState.UNKNOWN)\n         terminal.expect.return_value = (-1, None, Data(b\"\"))\n         self.assertEqual(driver._next_state()[0], FOSCliState.TN_TIMEOUT)\n         driver._handle_state(FOSCliState.CREDENTIAL_REJECTED)\n \n+    def test_retained_timeout_output_does_not_count_as_fresh_input(self):\n+        driver, _, _, logger, *_ = self.make_driver()\n+        terminal = Terminal(MagicMock(), logger)\n+        terminal._ensure_reader = lambda: None\n+        terminal._read_queue.put(b\"partial token\")\n+        driver._terminal = terminal\n+\n+        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.001):\n+            state, output, matched = driver._next_state()\n+            self.assertEqual(state, FOSCliState.UNKNOWN)\n+            self.assertEqual(bytes(output), b\"partial token\")\n+            self.assertFalse(matched)\n+            state, output, matched = driver._next_state()\n+            self.assertEqual(state, FOSCliState.TN_TIMEOUT)\n+            self.assertEqual(bytes(output), b\"partial token\")\n+            self.assertFalse(matched)\n+\n+    def test_kernel_panic_requires_kernel_diagnostic_and_raises(self):\n+        driver, terminal, commander, *_ = self.make_driver()\n+        pattern = driver.state_patterns[FOSCliState.KERNEL_PANIC.value]\n+        panic = (\n+            b\"Kernel panic - not syncing: VFS: Unable to mount root fs\\r\\n\"\n+            b\"CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.19.13 #1\\r\\n\"\n+        )\n+\n+        self.assertIsNone(\n+            re.search(\n+                pattern,\n+                b\"Kernel panic - not syncing: VFS: Unable to mount root fs\",\n+            )\n+        )\n+        match = re.search(pattern, panic)\n+        self.assertIsNotNone(match)\n+        terminal.expect.return_value = (\n+            FOSCliState.KERNEL_PANIC.value,\n+            match,\n+            Data(panic),\n+        )\n+\n+        with self.assertRaisesRegex(KernelPanicError, \"Kernel panic detected\"):\n+            driver.process_state()\n+\n+        commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))\n+\n \n if __name__ == \"__main__\":\n     unittest.main()",
        "lineStart": 1121,
        "lineEnd": 2108,
        "totalLines": 2108,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716615611,
      "end": 1793716615618
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d779c4001IebGaf4RA2m53v",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d76c04001vzNrO26VGTLzOG",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 81603,
    "input": 8833,
    "output": 27,
    "reasoning": 167,
    "cache": {
      "read": 72576,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d76c04001vzNrO26VGTLzOG",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716612100,
    "completed": 1793716615622
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 81603,
    "input": 8833,
    "output": 27,
    "reasoning": 167,
    "cache": {
      "read": 72576,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 34
step-start
{
  "type": "step-start",
  "id": "prt_1a1d78417001zFdYFqgDxdYK53",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d779d0001Wet13sBNqG25UI"
}
Reasoning
I now have the complete diff. Let me note the key details of the test change in test_common_terminal_driver.py:

```
-        with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "0"}):
+        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "64", "FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}, clear=True):
+            self.assertEqual(terminal_buffer_limit_bytes(), 64)
+        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "0"}, clear=True):
```

Wait — `patch.dict(..., clear=True)` clears the whole os.environ. `terminal_buffer_limit_bytes()` presumably uses get_env("FOS_TERMINAL_BUFFER_LIMIT_BYTES", aliases=...). Hmm — if the FTNT name is preferred, 64 wins over 32. Good.

Also the raw serial log test: `terminal._logger.log.assert_called_once_with(TRACE_LEVEL, "buffer: bytearray(b'matched')")`.

Now — the `test_kernel_panic_requires_kernel_diagnostic_and_raises` test: `commander.on_state.assert_called_once_with(FOSCliState.KERNEL_PANIC, Data(panic))`. But wait — in `process_state`, when a state matches, `output and not matched` is False (matched=True), so on_output is not called; `_process_state(state, output)` → state != CMD_PROMPT → `self._commander.on_state(state, output)`. Then `state != CMD_PROMPT` → `self._handle_state(state)` → `_kernel_panic()` raises KernelPanicError. But before that, on_state was called on the commander. And the commander's MagicMock. So the assert checks on_state was called with the Data. But `Data(panic)` — the driver passes the output Data from expect; the mock returns `Data(panic)` — same object, so assert passes.

Hmm wait, actually there's a subtlety: in `_process_state`, for KERNEL_PANIC: state != CMD_PROMPT and state != CMD_PROMPT_ECHO → `self._commander.on_state(state, output)` is called first, then `_handle_state(state)` raises. So the commander is notified before the exception propagates. OK.

Now, some deeper checks I should do before finalizing:

1. In `process_state` (fos_cli_driver.py line 104-119): when output and not matched: `self._commander.on_output(output)`, then for UNKNOWN `self._note_unknown_output()`, then `output = type(output)(b"")`. Then `self._process_state(state, output)` — for UNKNOWN: `on_state(UNKNOWN, empty Data)`. For TN_TIMEOUT: `on_state(TN_TIMEOUT, empty Data)`. Hmm wait — but for TN_TIMEOUT, `_process_state` at line 147: `elif state == FOSCliState.TN_TIMEOUT and self._last_known_state == CMD_PROMPT:` → tick + on_idle_prompt. But output is now empty. Previously (base), the timeout Data with content went to UNKNOWN state with full output. Now TN_TIMEOUT gets empty output. That's the designed change (full-buffer inspection happens in on_output before clearing).

Wait, actually — careful. In base, `_next_state` returned `(FOSCliState.TN_TIMEOUT if not output else FOSCliState.UNKNOWN)`. In head, `state = UNKNOWN if output.received_new_data else TN_TIMEOUT`. And in `process_state`, unmatched output goes to `commander.on_output(output)` (where capture happens — this is the new capture path for retained bytes), then output replaced with empty Data for on_state.

So for the TN_TIMEOUT case with retained bytes in the buffer (e.g. test_idle_read_exposes_retained_prompt_newline): expect returns Data(buffer) with received_new_data=False → state=TN_TIMEOUT, output has the retained b"\n". process_state: output truthy and not matched → commander.on_output(output) → CommandAttempt captures b"\n" (capture_output=True in the test spec) and discards. Then output replaced with empty → on_state(TN_TIMEOUT, empty) → commander records idle. That's the "test_idle_read_exposes_retained_prompt_newline" behavior: attempt.output == b"\n". OK.

2. Now — a potential double-count issue: `received_new_data` is set once new data arrives during THIS expect call. If the buffer retains data from a previous expect (not discarded), and no new data arrives, received_new_data=False → TN_TIMEOUT. Good.

3. `_enforce_buffer_limit` raises RuntimeError when buffer exceeds limit — inside expect loop. This propagates up through driver → launch bootstrap_spin → stop. Fine.

4. `_ByteQueue.put`: when queue full, `self._condition.wait()` — for the reader thread, if the consumer isn't reading, writer/reader blocks. Close: `read_queue.close()` notifies. OK.

Now, remaining verification tasks:

- Verify `BOOTSTRAP_HOSTNAME_REGEX` form (common.py lines 21-60). Let me read common.py fully to confirm regex definitions and that `set_prompt_patterns` handles it. Actually `set_prompt_patterns` is called with either str (hostname) or the BOOTSTRAP_HOSTNAME_REGEX bytes pattern. In fos_cli_driver.py line 293-298: `if isinstance(name_pattern, str): name_pattern = re.escape(name_pattern.encode())`. So bytes pattern passes through unchanged. BOOTSTRAP_HOSTNAME_REGEX must be a bytes literal. And `CLI_PROMPT_CONTEXT_PATTERN` in fos_commander.py uses `BOOTSTRAP_HOSTNAME_REGEX + ...` — string concatenation of bytes literals works only if it's a raw bytes literal, not compiled. So it's a bytes pattern. Good.

- One thing to check: `CLI_PROMPT_CONTEXT_PATTERN` uses BOOTSTRAP_HOSTNAME_REGEX which is the broad bootstrap hostname regex (GENERIC|DEFAULT|LICENSED alternation). After `set_prompt_patterns(hostname)` narrows the driver patterns, the commander's context extraction still accepts any hostname — fine, since context is extracted from the CMD_PROMPT output which already matched the driver's narrowed prompt pattern. But wait — is that true? The commander extracts context from CMD_PROMPT output regardless of which pattern matched. The driver's CMD_PROMPT pattern requires the configured hostname. But before `set_prompt_patterns` is called (during early bootstrap), the driver uses FOS_CLI_STATE_PATTERNS with GENERIC_HOSTNAME_REGEX presumably. Let me check common.py to see CMD_PROMPT pattern in base patterns. Need to read common.py lines 21-92.

Let me also double-check `_extract_prompt_context` uses `matches[-1]` — the LAST prompt line in the output. For CMD_PROMPT output that contains multiple prompt-like lines (e.g., echoed commands with prompts), the last one wins. Reasonable.

- Also check: `PROMPT_CONTEXT_REGEX` used in driver's narrowed CMD_PROMPT pattern: `^[ \t]*<hostname>(?P...)`? In driver: `rb"(?m)^[ \t]*" + name_pattern + PROMPT_CONTEXT_REGEX + rb"[ \t]*[#$][ \t]*\r?$"` where PROMPT_CONTEXT_REGEX = rb"(?:[ \t]+\([^)]+\))*". Good.

Now let me verify the commander's `_validate_completion` for closes_scope: `(attempt.spec.closes_scope or attempt.spec.fail_on_error) and COMMAND_FAILURE_PATTERN.search(...)`.

Note: `closes_scope` is `not continuation and line.strip().lower() in {"next","end"}`. For a continuation line that happens to be "next" (inside a quoted value ending with "next"?) — continuation=True → not closes_scope. Good.

Hmm, one issue: `closes_scope` matches ANY command line that is exactly "next" or "end" — including a plain string "next" submitted standalone (as in test_common_scope_errors test_cleanup_closing_failure_uses_bootstrap_error_policy with CommandSequence("close", ["end"])). That's intended.

Now, `_handle_context_loss` during cleanup: `_handle_work_error(RuntimeError(... "during cleanup ..." ))`. OK.

Next, let me re-examine `_complete_inflight` context-loss handling:

```
attempt.prompt_context_after = self._prompt_context
if self._in_context_reset: ... return
if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
    self._handle_context_loss(attempt)
    ...
```

`_prompt_context_changed` requires before AND after not None. `prompt_context_before = self._prompt_context` at dispatch. `_prompt_context` is set on CMD_PROMPT states. On the very first command after start, `_prompt_context` is None (no CMD_PROMPT seen yet? Actually commander.start is called after login typically; the first CMD_PROMPT sets context). If before is None (no context seen), context change is not detected → no context loss check. So the very first command dispatched before any CMD_PROMPT output has no context tracking. Acceptable design.

Also `_command_may_change_context`: commands starting with "config ", "edit ", or in {"next","end","abort","exit","quit"}, or "set vdom-mode multi-vdom". Note: this includes "exit" — the credentials feature's exit command may change context (logout) — exempt. Good.

But note: `command.startswith(("config ", "edit "))` — for a plain `set` command "config ..." doesn't start. Fine.

Now `_restart_active_block(attempt, reason)`: retries keyed by `attempt.block_index`. For cleanup commands, block_index=None. But `_restart_active_block` is only called for session-loss RESTART_BLOCK on feature commands (not cleanup — cleanup has its own retry accounting via _cleanup_retries and always appends left). Wait — for cleanup commands, `on_session_loss` is called? Let me check: `_on_session_loss` (the method around line 614 in diff): if `self._in_cleanup`: handle retries with _cleanup_retries and appendleft. Else feature path. And `_restart_active_block` is only in the feature path. So `attempt.block_index` is not None in feature path (set in `_dispatch_next`). But `_dispatch_command` is also called directly with block_index=None in `_restore_replay_context` ("abort" command). If a session loss occurs during the "abort" command... `_on_session_loss`: not in cleanup → feature path → action from feature.on_session_loss(attempt) where attempt.spec is the "abort" CommandSpec with default session_loss=RESTART_BLOCK → `_restart_active_block(attempt, "session lost")` with attempt.block_index=None → retries = self._recovery_retries.get(None, 0) → increments _recovery_retries[None]... and `self._pending = deque(self._active_commands)` — replays the whole block. Hmm, but also `_in_context_reset` handling: `_on_session_loss` at the top (from diff lines 791-799):

```
attempt = self._inflight
self._inflight = None
...
if self._in_context_reset:
    self._in_context_reset = False
    return
```

So session loss during the context-reset "abort" command clears `_in_context_reset` and returns — the replay target remains set and the pending replay happens after login. Bounded. Good — that's the covered test.

But what about session loss during the abort when _in_context_reset was already consumed... no, fine.

Another subtle case: `_restart_active_block` with block_index=None from an abort attempt — can that happen? The `_in_context_reset` check returns early, so the abort attempt never reaches the feature path. Good.

Now `test_feature_can_decline_replay_without_running_session_loss_callback`: `ip_command=IP_COMMAND if explicit_policy else spec` — wait, when explicit_policy=True, ip_command is the plain string IP_COMMAND and context_action=FAIL. When False, ip_command is the spec (session_loss=CONTINUE → context_loss defaults to FAIL) and context_action=None. Hmm: when explicit_policy=False, spec has session_loss=CONTINUE → default context_loss=FAIL → base Feature.on_context_loss returns FAIL → "feature declined replay". And feature.on_session_loss (MagicMock) not called. When explicit_policy=True: plain string spec → session_loss=RESTART_BLOCK → context_loss defaults RESTART_BLOCK... but context_action=FAIL → RecordingFeature.on_context_loss returns FAIL. Same result. The two subtests are somewhat redundant but exercise different paths. OK.

Now let me look for actual reportable findings. Given the extensive prior analysis resolved concerns (a)-(d), let me focus on remaining candidates:

Candidate 1 (P4): `CommandAttempt.on_output` double-extension risk? `output.discard(data)` with matched Data (no callback) → `.discarded = True`, no-op. With timeout Data, callback discards prefix. But there's a subtle issue: when `capture_output` is on and output is a MATCHED Data (not from timeout), `discard` is a no-op — fine since matched bytes were already consumed. When the SAME retained buffer is re-exposed on a later timeout, the previously-captured bytes get re-captured! Example: retained buffer has "garbage" from a timeout, commander.on_output captured it (attempt.output grew, discarded → buffer cleared). OK discarded clears buffer. But if a feature's on_output returns False without discard (doesn't recognize), bytes stay. Then a later timeout exposes the same bytes again → attempt.on_output extends output AGAIN with the same bytes → duplicated content in attempt.output. Is that a real problem? Consider a command with capture_output=True: retained bytes are captured and discarded immediately by CommandAttempt.on_output (first layer). So duplicates can't accumulate via attempt capture. For Feature.on_output: a feature that recognizes data must discard; if it returns True without discard... base.on_output returns False. License.on_output searches but doesn't discard — it only raises on failure. So on the next timeout, the same bytes are re-searched — idempotent. Fine.

But wait — the CMD_PROMPT_ECHO path: `on_prompt_echo` → on_output. If nothing consumes it, commander sends a newline. The echoed bytes remain buffered. Then the next expect matches the clean prompt. The echoed bytes were already part of the buffer before the prompt; after the prompt match, they're consumed (match includes only the prompt; bytes before remain? No — the CMD_PROMPT pattern matches the prompt line; match.end() consumes through the prompt; the earlier echo bytes are BEFORE the match start, and `del self._buffer[:match.end()]` deletes them too (prefix through match end). So the echo bytes are consumed by the prompt match. Fine.

Candidate 2: `terminal.expect` — after a match, bytes after the match stay buffered. If a command is in flight with capture_output=True, output after the match (e.g., the beginning of the next command's output) stays in the buffer. Then the next expect for the next state will return it as part of the matched output. Fine.

Candidate 3: Race in `_ensure_reader` — `self._read_queue = _ByteQueue(...)` resets the queue when reader is dead. But if `expect` is called from the main thread while a previous reader thread is still shutting down... `_reader.is_alive()` check guards. If the old reader died with an error, `read_queue.fail(error)` was called on the OLD queue which is replaced — the error is lost. Minor. But then the new expect would just time out. Acceptable.

Wait — actually there's a subtle bug: `_read_forever` on exception calls `read_queue.fail(error)` — but `read_queue` is the argument passed at thread creation, so it's the queue that was current when the thread started. If the queue was replaced (new expect call after reader died), the new queue never gets the error → hang until timeout. Minor reliability issue but pre-existing? The diff for terminal.py doesn't show `_ensure_reader` changes — the reader/writer threads appear pre-existing (diff only shows Data, expect, _discard_prefix changes). Let me verify: the diff hunk at line 915 starts "@@ -213,36 +216,46 @@" for expect; earlier hunks cover Data. So reader/writer thread logic is pre-existing. Skip.

Candidate 4: `_ByteQueue.put` — bounded blocking. Fine.

Candidate 5: In `fos_commander.py` `_recover_feature_error` — from diff:

```
def _recover_feature_error(self, *, at_idle_prompt=False):
    error = self._pending_feature_error
    if error is None or (
        self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
    ):
        return
    ...
```

I need the full body — from my earlier read of fos_commander.py (fully read, 687 lines). I don't have the exact contents in my context now (the earlier session's read is summarized). The summary says: "on_state: CMD_PROMPT clears `_recovering`/sets `_authenticated_once` — intended"; "_recover_feature_error with at_idle_prompt..." Hmm. I don't have full memory of lines 100-160 of fos_commander.py. I read the whole file earlier (1-687), but the summary only captured highlights. For accurate anchors, I may need to re-read specific ranges of fos_commander.py. Let me re-read the middle portion (lines 95-330) to have precise line numbers for the parts I might cite.

Actually, which findings do I actually plan to report? So far my analysis has found:

1. P4: `_cleanup_retries` keyed by `id(spec)` — dict entries persist until popped at `_complete_inflight` (only popped when in_cleanup completes) or cleared in `continue_after_error`. If a cleanup spec fails with context loss during cleanup... `_handle_context_loss` when in_cleanup calls `_handle_work_error` → continue_after_error clears `_cleanup_retries`. If a cleanup command is replayed after session loss, `_cleanup_retries[id(spec)]` set; the spec is appended back to `self._cleanup`. When it's dispatched again and completes, popped. If the cleanup never completes (feature error path), `continue_after_error` clears. So the dict is bounded. Non-issue. Skip.

2. P4: `state_case` duplicated `completion = (FOSCliState.CMD_PROMPT,)` branches — trivially mergeable. This is a nitpick; probably not worth reporting. Actually the two branches: first for (CREDENTIAL_REJECTED, PROVIDE_USERNAME), second for (CREDENTIAL_ACCEPTED, SESSION_LOST, CMD_PROMPT_ECHO) — both set the same value. The first branch exists because those states need a follow-up prompt; the second likewise. They're semantically different groups that happen to share the same completion. Merging is a minor cleanup. I could report as P4 maintainability. Hmm — "Do not inflate stylistic preferences". This is a legitimate small simplification. I'll consider including it as P4... It's borderline; the review guidelines say findings must be actionable and useful. A duplicate identical assignment in adjacent branches is minor. I might include it as a P4.

3. Potential real issue: In `fos_commander._dispatch_next`, when `self._pending_feature_error is not None` it returns early — but `_recover_feature_error` is called on CMD_PROMPT in on_state before dispatch. OK.

4. Let me reconsider `_restore_replay_context` interplay: `_dispatch_command(CommandSpec("abort", suppress_output=True))` — the abort command's completion: default completion state CMD_PROMPT. When the abort completes at a prompt, `_complete_inflight` → `_in_context_reset` True → set False → `_dispatch_next()` → `_restore_replay_context` checks context vs target. Good.

But: the abort command has `expected_completion_state=None`, `fail_on_error=False`, `closes_scope` False ("abort" not in {"next","end"}). Also `_command_may_change_context("abort")` → True → context change after abort exempt. Good.

But what about the abort command being captured? Not capture_output → attempt output discarded? No — not captured, output falls to feature.on_output then _inspect_output. Fine.

5. Another candidate: `_handle_context_loss` → `_restart_active_block` sets `_replay_context_target = self._block_prompt_context`. If `_block_prompt_context` is None (block submitted before any CMD_PROMPT seen — e.g., the first block of the first feature after start... wait, `submit_block` is called from feature.activate() which is called at CMD_PROMPT processing (features activate after ready). Actually `_activate_next_feature` → begin_activation/activate — called when? On the first CMD_PROMPT after start. At that point, `self._prompt_context` may already be set by on_state CMD_PROMPT handling? Order in on_state: context extraction happens BEFORE dispatch (`_dispatch_next` is called at the end of on_state presumably). Let me check on_state flow (diff hunk @@ -242,10 +269 and @@ -275,13 +310): on_state sets context first (CMD_PROMPT), then `_recover_feature_error`, then session-lost handling, then `_complete_inflight`, then at the end `if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES: self._dispatch_next()`. So by the time features activate, `_prompt_context` is set. So `_block_prompt_context` None only if a block was submitted outside a prompt (e.g., license feature submitting confirm block during CONFIRMATION state — `on_command_executed` → submit_block → `_block_prompt_context = self._prompt_context` which was set from the earlier CMD_PROMPT). `_replay_context_target = None` when block context None → `_restore_replay_context` returns True immediately. Benign (confirmed earlier).

6. Now a REAL potential issue I should examine: `_restart_active_block` resets `self._pending = deque(self._active_commands)`. But if the session/context loss happened during a CLEANUP command — no, handled separately. During `_in_context_reset` — handled early. OK.

7. Another candidate: `on_state` early return paths. From diff hunk @@ -275,13 +310: 

```
        if state == FOSCliState.CREDENTIAL_ACCEPTED:
            self._authenticated_once = True
            self._recovering = False
            return
-        if state == FOSCliState.CMD_PROMPT:
-            self._authenticated_once = True
-
        if self._inflight and state in (
            self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
        ):
            self._complete_inflight(state)
            return
```

So the CMD_PROMPT-specific auth handling moved to the top (lines 574-581 in diff numbering: head lines ~272-280). Need exact head line numbers: I read fos_commander.py fully earlier; head line numbers for on_state CMD_PROMPT context block — the diff hunk header says @@ -242,10 +269,18 @@ meaning head line 269 for that hunk. The context extraction block is at head lines ~272-280.

Let me now also check `fos_commander.py` `_on_session_loss` full head content (diff hunk @@ -466,11 +614,24). I have head line numbers: `_on_session_loss` starts around head line 610-660.

For the final report I need precise anchors only for the findings I report. Let me decide what findings to report. 

Honest assessment: this PR looks well-engineered with strong test coverage. My four concerns from earlier were resolved. Let me do a few more targeted checks for real defects:

Check A: `_flatten_quoted_lines` with a single line: `completion_states = ()` → default CMD_PROMPT completion. `expected_completion_state = CMD_PROMPT if validate_prompt`. For SetValue with validate_prompt=False → expected None. OK.

But for a plain multi-line STRING submitted via flatten_commands: `_flatten_quoted_lines(value.split("\n"))` with validate_prompt=True → continuation lines expect MULTILINE_PROMPT. Is that right for a plain multi-line string like "set comment \"a\nb\""? Yes — quoted value spans lines, each line ends with continuation prompt ">". Matches README. Good.

But hmm — what about a plain multi-line string that is NOT a quoted value, e.g. "show run\nmore"? It would be sent line-by-line expecting continuation prompts after the first line. Misuse — but the README documents multi-line strings as quoted values. Acceptable.

Check B: `SetValue.flatten` with value containing "\r" — `str(value).strip().splitlines()` splits on \r\n etc. CommandSpec line can't contain "\n" (post_init raises) but CAN contain "\r"? No — `__post_init__` raises if "\r" in line OR "\n" in line. `splitlines()` splits on \r, \n, \r\n, \v, \f, \x1c-\x1e, \x85, \u2028, \u2029. So splitlines removes \r. But other unicode line separators (\x85 NEL etc.) — splitlines splits on them, so they won't survive into lines. What about a value containing "\r" alone? splitlines splits on it. So lines never contain \r\n. What if value = "a\rb"? splitlines → ["a", "b"]. Fine. So CommandSpec post_init can't be triggered by SetValue? What about a lone line containing "\x0b" (vertical tab)? splitlines splits on \x0b too. So safe.

But `flatten_commands` for plain strings: `value.split("\n")` — a string "set x \"a\rb\"" (with \r but no \n) → single line containing \r → CommandSpec post_init raises ValueError. Edge case, error is clear ("CLI commands must contain exactly one line"). Startup config parser: text mode normalizes... reads with universal newlines → \r\n → \n. A lone \r in the file stays? In text mode, Python's universal newlines converts \r alone to \n as well. So \r won't survive. OK.

Check C: `_startup_config_commands` — line 56: `raw_line.removesuffix("\n")`. In text mode, \r\n → \n. Lone \r → \n. So fine.

But WAIT: there's a subtle issue with `removesuffix("\n")` vs the last line without trailing newline — fine.

Another: a line consisting of only "\n" inside a quote → `line = ""`, pending non-empty → `pending.append("")`? Only if quote is not None or escaped — a blank line inside a quoted value: quote is not None → pending.append("") — preserved. README says blank lines inside quoted values preserved. Good.

Check D: `parse_startup_config` — after `_startup_config_commands` yields a joined multi-line command, `line.startswith("config ")` — the first line was lstripped, so "config system dns" with the rest being continuation lines of a quoted value... For example:

```
config system global
    set alias "my
    hostname"
end
```

The `set alias "my\n hostname"` becomes one logical command; parser adds it as a child of the global block. Good.

But consider a quoted value that CONTAINS a line starting with "config " — e.g. set description "x\nconfig evil\ny". The logical command is `set description "x\nconfig evil\ny"` — starts with "set " → child. Good. But what about a quoted value spanning lines where the FIRST line is `set description "a` and subsequent `config`-looking lines are part of the quote — handled since only the first line of the logical command is checked. Good.

Check E: A multi-line quoted value inside a config block that starts with... all fine.

Check F: What about `edit` inside a quoted value with name spanning lines? e.g. `edit "port\n1"` → logical command `edit "port\n1"` → startswith("edit ") → EditBlock("port\n1") → flatten → open_line contains \n → flatten_commands splits via _flatten_quoted_lines → first line `edit "port`, continuation `1"`. Works.

Check G: `ConfigBlock(line[7:])` — value could contain trailing content... fine.

Now check H:fos_commander `_inspect_output` — I need to check what it does (from my earlier full read; summary says "on_output order: CommandAttempt → Feature → _inspect_output"). _inspect_output handles console output pattern and maybe session-lost? I don't recall exactly. It was in the file. For the report I may not need it.

Check I: The `exit` command spec has `capture_output=True, fail_on_error=True` and `session_loss=CONTINUE` → default context_loss=FAIL. Also `_command_may_change_context("exit")` → True → context change exempt. But WAIT — there's a subtle interplay: `exit` has session_loss=CONTINUE, so when logout happens, on_session_loss returns CONTINUE → `_pending.clear()`... but the pending for the admin-relogin block has only "exit" which is already in flight. `_pending.clear()` clears pending (empty anyway). Then the feature block completes? Let's trace: session loss during exit → `_on_session_loss`: `_in_cleanup` False → `_schedule_feature_cleanup`? From diff line 812: `self._schedule_feature_cleanup(self._active_feature, "interruption")` then `action = self._call_feature(self._active_feature.on_session_loss, attempt)` — wait, `_schedule_feature_cleanup` is called BEFORE the action? Let me look at the head code again — I need the actual `_on_session_loss` body. From the diff:

```
@@ -466,11 +614,24 @@
             return
         attempt = self._inflight
         self._inflight = None
         self._suppression.close()
         self._suppression = ExitStack()
+        if self._in_context_reset:
...
         if self._in_cleanup:
+            retries = ...
             self._cleanup.appendleft(attempt.spec)
             self._in_cleanup = False
             return
         self._schedule_feature_cleanup(self._active_feature, "interruption")
         action = self._call_feature(
             ...
```

So `_schedule_feature_cleanup(active_feature, "interruption")` is called — that registers cleanup actions? Wait — `_schedule_feature_cleanup(feature, when)` presumably queues the feature's cleanup actions (reversal blocks) to run on interruption. Hmm, that means when a session loss happens during ANY feature command, the feature's cleanup/reversal is scheduled? That seems to be the semantics: on interruption, the feature's reversal blocks are queued so its work can be undone... but then the action handler may restart the block anyway. This is pre-existing behavior (the `_schedule_feature_cleanup` line is unchanged context in the diff).

Hmm wait — actually, does `_schedule_feature_cleanup` queue reversal blocks? If so, for CredentialsFeature, reversal_blocks() — base returns []. OK.

But for the "exit" session loss (CONTINUE → `_pending.clear()`): the block's remaining commands are cleared, then... does the block complete? After session loss, reconnect → prompt → `_dispatch_next` → `_pending` empty → `_call_feature(on_block_complete)` → CredentialsFeature inherits StaticFeature.on_block_complete? StaticFeature presumably marks block complete and when the last block is done, marks feature complete via on_complete callback. The admin-relogin block is the last block → feature_complete → on_complete → _activate_desired_credentials (idempotent). Then following features wait for authentication — the commander requires `_authenticated_once` before activating next feature. After exit logout, the driver answers login prompts → CREDENTIAL_ACCEPTED or CMD_PROMPT sets `_authenticated_once`. Then next feature activates. Matches test expectations.

OK. Now Check J: `fos_commander.on_output` and `on_prompt_echo` — need head lines if cited. I might not cite them.

Check K: LICENSE feature `on_command_executed(self, command, state)` — signature `command` vs other features use `attempt`. Naming inconsistency (pre-existing? license.py not in changed list... wait, license.py isn't in the changed file list! The changed files are base, credentials, pki, startup_config. So license.py is context only. Good — skip.

Check L: `pki.py` change is comment-only. Skip.

Check M: `common.py` — KERNEL_PANIC inserted between MULTILINE_PROMPT and UNKNOWN. Existing comparisons `state.value < FOSCliState.UNKNOWN.value` treat KERNEL_PANIC as a "known" state → `_clear_unknown_stall`, `_last_known_state = KERNEL_PANIC`. Fine.

Check N: launch.py `bootstrap_spin` — KernelPanicError: stop + raise. But `except KernelPanicError` comes BEFORE `except Exception` — correct ordering. 

Check O: The `main()` function: `logger.setLevel(parse_log_level(get_env("FOS_LOG_LEVEL")))` → FTNT_LOG_LEVEL alias. README documents FTNT_LOG_LEVEL. Good.

Check P: Now the docs check — README.md's env table: does it document `FTNT_TERMINAL_BUFFER_LIMIT_BYTES`? Not in the table (lines 89-113). It's referenced in docker/README.md line 53-54 ("Retained terminal data is bounded by `FTNT_TERMINAL_BUFFER_LIMIT_BYTES`, which defaults to 1 MiB") — that's docker README (internal docs). Is FTNT_TERMINAL_BUFFER_LIMIT_BYTES pre-existing or new? terminal.py `terminal_buffer_limit_bytes()` — the diff doesn't touch it (it's outside the hunks), so pre-existing. The docker README mentions it — pre-existing too? The docker README diff hunks don't touch that bullet (lines 53-59 are context in the first hunk? The hunk @@ -35,12 +35,15 @@ covers lines 35-47ish; the buffer-limit bullet at lines 53-59 is context, unchanged). So pre-existing. Skip.

Check Q: README.md updated paragraph matches implementation — verified above. Good.

Check R: docker README's new "Scope-closing commands" paragraph says: "It follows the bootstrap error policy: abort normally, or skip the failed feature when `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`." — Hmm, note the env is `FOS_EXIT_ON_BOOTSTRAP_ERROR`/`FTNT_EXIT_ON_BOOTSTRAP_ERROR`. README main table documents `FTNT_EXIT_ON_BOOTSTRAP_ERROR`. Docker README says `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. Both spellings are accepted (env aliases), and docker README consistently uses FOS_ names elsewhere (line 311: `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` — wait, docker README line 311 says "With `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`". And the new paragraph says `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. Inconsistent naming within the same document — the new text introduced in this PR uses the legacy FOS_ spelling while the rest of the document uses FTNT_. Minor documentation inconsistency (P3/P4). Let me verify: docker README line 137 in head: "It follows the bootstrap error policy: abort normally, or skip the failed feature when `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`." And line 311: "With `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, a failed feature is logged and skipped...". Both refer to the same variable with different spellings. Since env.py accepts both, it's functionally fine, but it's an inconsistent doc reference introduced by this PR's added paragraph. The main README documents the FTNT_ spelling as "the documented environment interface". So the new docker README paragraph should use `FTNT_EXIT_ON_BOOTSTRAP_ERROR`. This is a legitimate P3/P4 documentation finding. Priority: P4 (minor doc nit, no functional impact) — or P3? It's user-facing documentation inconsistency; the variable works with both spellings. I'd say P4. Hmm, "For missing docs/schema entries, anchor the finding to the introducing change and name the missing counterpart." This is a doc inconsistency, P4 seems right. Actually since the documented public interface is FTNT_ and the new paragraph names FOS_, a user copying that name gets working behavior (alias). Low impact → P4.

Check S: The main README "Startup Config" section says "the closing line must return to a command prompt. An unexpected prompt follows the bootstrap error policy." — Hmm, is that accurate? For a multi-line quoted value, the LAST line's expected_completion_state=CMD_PROMPT (validate_prompt=True default for flatten_commands path). If it doesn't return to CMD_PROMPT (e.g., returns to MULTILINE_PROMPT because the quote wasn't closed properly — but unterminated quotes raise at parse time). An unexpected prompt (e.g. CONFIRMATION?) — the completion_states for the last line are (CMD_PROMPT, MULTILINE_PROMPT), so the command would complete at MULTILINE_PROMPT too → then expected_completion_state=CMD_PROMPT mismatch → RuntimeError → bootstrap error policy. Accurate.

Wait, there's a subtlety: for the last line, completion_states=(CMD_PROMPT, MULTILINE_PROMPT) — if FortiOS returns to MULTILINE_PROMPT (another continuation prompt) even though the quote was closed... can't happen: after the closing quote, the CLI returns to the edit/config prompt, not continuation. Unless the command was accepted and FortiOS prompts ">" again — no.

Hmm, but actually there IS an edge: `expected_completion_state=CMD_PROMPT` for the last line, but the commander's `_complete_inflight` runs `_validate_completion` AFTER the context-change check. For the last line of a quoted value inside a config block, `_command_may_change_context`? The spec has continuation=False for the last line (index > 0 only for lines after the first — wait: `continuation=index > 0` → first line continuation=False, subsequent lines continuation=True). So the LAST line of a multi-line value has continuation=True! So `_command_may_change_context` returns False for continuation lines... and `closes_scope` = `not self.continuation and ...` → for continuation lines, closes_scope=False. Hmm wait — for the last line: continuation=True (since index = len-1 > 0 for multi-line). So `closes_scope` False — meaning the last line's output is NOT force-captured and its failure not checked by COMMAND_FAILURE_PATTERN! But `_flatten_quoted_lines` sets `capture_output=True` explicitly for all lines. So capture happens anyway. But fail_on_error: `_flatten_quoted_lines(lines, fail_on_error=...)` — for flatten_commands path, fail_on_error=False → the "Command fail. Return code" check only happens if fail_on_error or closes_scope. For a multi-line `set` command whose last line is a continuation (continuation=True), a failure on the last line is NOT detected unless the block's closing next/end catches it. Hmm — for SetValue (default fail_on_error=False? SetValue.__init__ default fail_on_error=True). SetValue defaults fail_on_error=True → all its lines get fail_on_error=True → failure detected. For plain multi-line strings via flatten_commands: fail_on_error=False and last line continuation=True → no failure detection on the set command. But the surrounding config block's `end` closes_scope → checked. If the set is at top level (no config block), a failure goes undetected... but a top-level multi-line `set` isn't valid FortiOS anyway. Acceptable.

Wait, actually — reconsider `continuation` semantics: `continuation=index > 0` means all lines except the first are continuations. The first line is the actual command start; continuation lines are continuations of the quoted value. `closes_scope` requires `not continuation` — so only a standalone "next"/"end" (index 0 of its own logical command) counts. Good.

And `_command_may_change_context` returns False for continuation=True — meaning continuation lines may NOT change context (context change after a continuation line IS a context loss). Correct: a continuation line that ejects from the edit scope is unexpected.

Hmm wait, but there's a wrinkle: for the FIRST line of a multi-line quoted `set` command — `continuation=False`. Is `set ...` in the `_command_may_change_context` list? No — command.startswith(("config ","edit ")) false, not in {"next","end","abort","exit","quit"}, not vdom-mode. So a context change after the first line of a multi-line set is a context loss → RESTART_BLOCK (default). Good.

Check T: One more important trace — the driver `_next_state` when matched: the CMD_PROMPT output Data is passed to commander.on_state. The commander's `_extract_prompt_context(output)` searches CLI_PROMPT_CONTEXT_PATTERN in the matched output. The matched output for CMD_PROMPT is the matched PREFIX (consumed bytes) — includes the prompt line. Good. But note: the consumed bytes include everything BEFORE the match too (match.start() to end from buffer start? `consumed = bytes(self._buffer[:match.end()])` — yes, from buffer start through match end). So the output includes preceding output lines. The regex `(?m)^[ \t]*HOST(?: contexts)*[ \t]*[#$][ \t]*\r?$` with finditer → takes the LAST match. If the buffer had an earlier prompt line (e.g. from previous output) and the current match is the latest prompt, `matches[-1]` picks the last prompt line in the consumed output. Good.

But here's a subtle scenario: CMD_PROMPT output contains a prompt-like line INSIDE command output (e.g., "show run" output containing "fw (global) #"). The last match is the actual prompt (it ends the consumed stream). Since the match consumed through the actual prompt, the actual prompt is the last line → matches[-1] is it. Good.

Check U: `_extract_prompt_context` returns None when no matches — then `_prompt_context` unchanged (stale). When could CMD_PROMPT state fire with output not containing a parseable prompt? The driver's CMD_PROMPT pattern requires hostname + context + [#$]. The commander's extraction requires the same shape with BOOTSTRAP_HOSTNAME_REGEX (broad). If the driver was narrowed to a specific hostname, the output matches the narrowed pattern which the broad regex also matches. Before narrowing, driver uses base patterns — do the base CMD_PROMPT patterns have the same shape? Presumably GENERIC_HOSTNAME_REGEX + context. So extraction succeeds. What about CMD_PROMPT matched via a pattern variant that doesn't include context (e.g., FortiProxy prompt "proxy #")? BOOTSTRAP_HOSTNAME_REGEX is "GENERIC|DEFAULT|LICENSED hostname alternation" — includes generic. Should be fine.

Edge: what if the CMD_PROMPT output's last prompt-like line differs from the actual matched prompt? E.g., consumed output contains TWO prompt lines: "fw (a) #\r\n" (stale, from earlier unmatched bytes) then "fw (b) #" (the match). matches[-1] = the b one — correct (latest). Good.

Check V: Now, an important correctness check — `_prompt_context_changed` uses `attempt.prompt_context_before` = `self._prompt_context` at dispatch time. But `self._prompt_context` is updated on EVERY CMD_PROMPT — including prompts observed between dispatch and completion? Between dispatch and completion, on_state with CMD_PROMPT would complete the inflight (completion_states) — so no intermediate prompts. But MULTILINE_PROMPT states don't update context. OK.

Hmm — one gap: `_extract_prompt_context` only updates on CMD_PROMPT. But a command that changes context could also return to a prompt that the driver matched as CMD_PROMPT — that's the check. Fine.

Check W: `_restart_active_block` after context loss: `_replay_context_target = self._block_prompt_context` — the context where the block STARTED. After replay, `_restore_replay_context` waits until prompt context == target. But `_block_prompt_context` was captured at submit_block time — if the block was submitted while at `(Interim)` and the loss moved us to `(interface)`... target=(Interim). After abort, context=(Interim) → proceed. In test_partial_scope_is_aborted_once_before_replay, target is the top-level? Block = ConfigBlock submitted at prompt() (top-level, context=()). Loss: prompt(commander, "interface") — after `config system interface` was dispatched and completed... wait the test: prompt() [top] → enter_interface [interface, port1] → prompt(commander, "interface") — the IP command completed but returned to (interface) instead of (port1) → context changed from (port1,Interim) to (interface,Interim) → context loss → RESTART_BLOCK → target = _block_prompt_context = () (top-level, where submit_block happened). Current context = (interface, Interim) ≠ () → abort dispatched → prompt() → context () == target → replay. Matches test.

Check X: Now let me think about `_dispatch_command` for the abort: `self._inflight.prompt_context_before = self._prompt_context` — fine. `if self._active_feature and not self._in_context_reset: on_command_dispatched` — during context reset, `_in_context_reset=True` → feature NOT notified of the abort dispatch. Good (abort is synthetic).

Check Y: `_complete_inflight` for the abort: `_in_context_reset` True → set False → `_dispatch_next()` → `_restore_replay_context` → context==target? proceed with replay. Good.

But hmm — `_complete_inflight` for the abort runs BEFORE `_validate_completion` — so the abort's own completion state (CMD_PROMPT default) isn't validated, and importantly, the abort's output isn't checked for failure (fail_on_error False anyway). Fine.

Check Z: Potential issue — during `_in_context_reset`, if the abort times out repeatedly... eventually the driver's stall recovery or bootstrap failure handles it. Bounded by EXPECT_TIMEOUT loop in process_state? process_state loops while not ready and within PROCESS_SPIN_SECONDS (10s). The abort would keep timing out → on_state(TN_TIMEOUT) → commander.on_state(TN_TIMEOUT, empty) → inflight completion_states (CMD_PROMPT) not matched → no completion. After spin ends, main loop continues calling work → bootstrap_spin again. Indefinite? The VM has an overall healthcheck. Not a new issue class.

OK. Now let me also verify the `credentials.py` `_activate_desired_credentials` when "exit" dispatched: `on_command_dispatched` fires BEFORE the command is written. So credentials switch BEFORE exit is sent. The session is still authenticated as admin with old password — but we're not sending credentials now, just exit. After exit, login prompt: driver._credentials = desired. Good. But what if the exit command FAILS (fail_on_error=True) — e.g., "Command fail" — then _validate_completion raises → bootstrap error. Credentials already switched to desired but we're still logged in with the old session — subsequent commands run in the old session; later logins would use desired. Acceptable.

Now — the activate_desired in on_command_dispatched also calls `self.vm.activate_desired_credentials()` which calls `driver.remember_current_credentials()` — snapshotting old credentials for recovery. Good.

One more check: `_activate_desired_credentials` idempotent via `_desired_credentials_activated`. But the `on_complete` callback also calls it (idempotent). Good.

Now — the tests. Do they cover the new behavior? test_common_recovery, test_common_scope_errors, test_common_admin_credentials (new); stack_parsing additions (abort recovery through serial driver, failed next); stack_boundaries (initial_prompt variants, retained newline); terminal_driver (timeout retention, kernel panic, FTNT env aliasing). Good coverage.

Let me now also check `test_common_terminal_driver.py` head around the `make_driver` and the new tests to make sure I have line numbers right (I read the file fully earlier — 332 lines? wait, earlier read of test_common_terminal_driver.py showed "first 600 lines" per summary, but the file is 332 lines... Hmm, that's inconsistent. The diff says the file is ~300 lines (hunk @@ -219,8 +281,52 suggests head file ~330 lines). So the file is 332 lines and I've read it entirely. Good.

Now, are there any REAL defects to report? Let me think harder about a few specific areas:

1. `Terminal.expect` — `stable_match = re.search(regex_list[index], consumed)`: if the match object's group spans... consumed = buffer[:match.end()] — the same text, so stable_match is identical. Why re-run? Because after `del self._buffer[:match.end()]`, the match object's .string references the mutated bytearray? Actually match objects keep a reference to the ORIGINAL string passed (they don't re-scan), but `match.string` is the bytearray that was mutated — `match.group()` returns bytes captured at match time (stored in the match object), so it's stable. The re-search is defensive but costs an extra regex run per match. Minor performance nit (P4?) — "repeated expensive work"? It's one extra regex run per matched event — negligible. Skip.

2. `_ByteQueue.get` with `remaining=None` (no deadline): while loop `self._condition.wait()` then `continue` — after wait returns, re-checks conditions. Fine. But if data arrives and chunks empty? get returns b"" when queue empty and not closed — only possible on spurious wakeup after wait timeout... with deadline=None, wait() blocks indefinitely until notify. OK.

3. `Terminal.close()`: `read_queue.close()` — but the reader thread might be blocked in `read_very_eager` (a blocking read?) — stop_reader set; the thread returns after current read. If `read_very_eager` blocks forever (scrapli read), join(1) times out — daemon thread, process exit fine.

4. `fos_commander._recover_feature_error` — I need to see the actual implementation to check for issues. Let me re-read fos_commander.py lines 95-160 to have it fresh.

5. Also `_inspect_output` and `on_output`/`on_prompt_echo` in fos_commander — re-read lines 330-470ish.

Let me re-read fos_commander.py sections to refresh and get exact line numbers. Actually, since my findings list is currently thin, let me re-read the whole fos_commander.py once more carefully to hunt for defects. It's 687 lines. Let me read 1-350 and 350-687.

Actually I already read the whole file earlier in the session (before the summary was made). But my context now only has the summary's highlights. I should re-read it to do a proper final check. Let me do that now.
I have the full diff now. Let me re-read `fos_commander.py` in full to finalize the correctness review with precise line anchors.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_commander.py",
  "limit": 360
}

Output

<path>/source/head/fortinet/common/fos_commander.py</path>
<type>file</type>
<content>
1: """Event-driven command scheduler for the FortiOS CLI."""
2: 
3: import datetime
4: import re
5: from collections import deque
6: from contextlib import ExitStack
7: from dataclasses import dataclass
8: 
9: from .cli_commands import (
10:     CleanupAction,
11:     CommandAttempt,
12:     CommandSequence,
13:     CommandSpec,
14:     ConfigBlock,
15:     ContextLossAction,
16:     SessionLossAction,
17:     flatten_commands,
18: )
19: from .terminal import Data
20: from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL
21: 
22: DISPATCHABLE_COMPLETION_STATES = {
23:     FOSCliState.CMD_PROMPT,
24:     FOSCliState.CONFIRMATION,
25:     FOSCliState.MULTILINE_PROMPT,
26: }
27: COMMAND_FAILURE_PATTERN = re.compile(
28:     rb"(?mi)^\s*Command fail\.\s*Return code\s+(-?\d+)"
29: )
30: CLI_PROMPT_CONTEXT_PATTERN = re.compile(
31:     rb"(?m)^[ \t]*" + BOOTSTRAP_HOSTNAME_REGEX
32:     + rb"(?P<context>(?:[ \t]+\([^)]+\))*)[ \t]*[#$][ \t]*\r?$"
33: )
34: 
35: 
36: @dataclass
37: class _StandardOutputContext:
38:     feature: object
39:     callback: object
40:     phase: str = "inspect"
41:     restore: bool = False
42: 
43: 
44: class FOSCommander:
45:     MAX_COMMAND_RECOVERY_RETRIES = 1
46:     _CONSOLE_OUTPUT_PATTERN = re.compile(rb"(?mi)^\s*set output (more|standard)\s*\r?$")
47:     _CONSOLE_INSPECT_LINE = "show full-configuration system console"
48:     _CONSOLE_STANDARD_LINE = "set output standard"
49: 
50:     def __init__(self, terminal, logger, continue_on_error=False):
51:         self.terminal = terminal
52:         self.logger = logger
53:         self._features = deque()
54:         self._active_feature = None
55:         self._active_commands = ()
56:         self._pending = deque()
57:         self._inflight = None
58:         self._attempt_number = 0
59:         self._session_epoch = 0
60:         self._recovering = False
61:         self._cleanup = deque()
62:         self._cleanup_actions = {}
63:         self._in_cleanup = False
64:         self._standard_output_context = None
65:         self._suppression = ExitStack()
66:         self._ready = False
67:         self._startup_complete = False
68:         self._feature_errors = []
69:         self._authenticated_once = False
70:         self._completed_messages = deque()
71:         self._start_time = datetime.datetime.now()
72:         self._continue_on_error = continue_on_error
73:         self._pending_feature_error = None
74:         self._current_state = None
75:         self._callback_failed = False
76:         self._prompt_context = None
77:         self._block_prompt_context = None
78:         self._recovery_retries = {}
79:         self._cleanup_retries = {}
80:         self._replay_context_target = None
81:         self._context_reset_attempted = False
82:         self._in_context_reset = False
83: 
84:     def _call_feature(self, callback, *args):
85:         """Run a feature callback and apply best-effort policy at this boundary."""
86:         try:
87:             return callback(*args)
88:         except Exception as error:
89:             self._handle_work_error(error, from_callback=True)
90:             return None
91: 
92:     def _handle_work_error(self, error, *, from_callback=False):
93:         """Apply the configured failure policy after feature/recovery decisions."""
94:         if not self._continue_on_error:
95:             raise error
96:         if from_callback:
97:             self.logger.exception("Bootstrap feature callback failed")
98:         else:
99:             self.logger.error("Bootstrap work failed: %s", error, exc_info=error)
100:         self._pending_feature_error = error
101:         self._callback_failed = True
102: 
103:     def _recover_feature_error(self, *, at_idle_prompt=False):
104:         error = self._pending_feature_error
105:         if error is None or (
106:             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt
107:         ):
108:             return False
109:         failed_work = self.continue_after_error(error, at_command_prompt=True)
110:         if failed_work is None:
111:             return False
112:         self._pending_feature_error = None
113:         self.logger.error(
114:             "Bootstrap work %s failed; continuing with remaining features "
115:             "because FOS_EXIT_ON_BOOTSTRAP_ERROR=false",
116:             failed_work,
117:         )
118:         self._dispatch_next()
119:         return True
120: 
121:     @property
122:     def ready(self):
123:         return self._ready
124: 
125:     @property
126:     def busy(self):
127:         return self._inflight is not None or bool(self._pending) or bool(self._cleanup)
128: 
129:     @property
130:     def startup_complete(self):
131:         """Whether the initial feature queue has drained, with or without errors."""
132:         return self._startup_complete
133: 
134:     @property
135:     def feature_errors(self):
136:         """Bootstrap feature errors recorded while best-effort mode is active."""
137:         return tuple(self._feature_errors)
138: 
139:     def continue_after_error(self, error, at_command_prompt):
140:         """Skip failed work only when the CLI is back at a usable prompt.
141: 
142:         A login rejection after the driver's credential recovery attempts, or
143:         an error during an interactive prompt, cannot be recovered by sending
144:         the next feature's commands, so automatic bootstrap must stop.
145:         """
146:         if not at_command_prompt or self._ready:
147:             return None
148:         if self._active_feature is None and not self._in_cleanup:
149:             return None
150: 
151:         if self._active_feature is not None:
152:             failed_name = self._active_feature.name
153:             self._pending.clear()
154:             self._active_commands = ()
155:             self._inflight = None
156:             self._suppression.close()
157:             self._suppression = ExitStack()
158:             self._finish_standard_output_context(self._active_feature)
159:             self._schedule_feature_cleanup(self._active_feature, "interruption")
160:             self._active_feature = None
161:         else:
162:             failed_name = "cleanup"
163:             self._inflight = None
164:             self._suppression.close()
165:             self._suppression = ExitStack()
166: 
167:         self._in_cleanup = False
168:         self._replay_context_target = None
169:         self._in_context_reset = False
170:         self._cleanup_retries.clear()
171:         self._feature_errors.append((failed_name, str(error)))
172:         return failed_name
173: 
174:     def record_feature_error(self, name, error):
175:         """Record a recoverable bootstrap problem without stopping the queue."""
176:         self._feature_errors.append((name, str(error)))
177:         self.logger.info("Using recovery for %s: %s", name, error)
178: 
179:     def resolve_feature_error(self, name, resolution):
180:         """Clear a recoverable feature error after its condition is resolved."""
181:         remaining = [
182:             (feature_name, error)
183:             for feature_name, error in self._feature_errors
184:             if feature_name != name
185:         ]
186:         resolved_count = len(self._feature_errors) - len(remaining)
187:         if resolved_count:
188:             self._feature_errors = remaining
189:             self.logger.info(
190:                 "Resolved %s bootstrap recovery after %s",
191:                 name,
192:                 resolution,
193:             )
194: 
195:     def start(self, features):
196:         self._features.extend(features)
197: 
198:     def tick(self):
199:         if self._pending_feature_error is not None:
200:             return
201:         if self._active_feature and hasattr(self._active_feature, "tick"):
202:             self._call_feature(self._active_feature.tick)
203: 
204:     def submit_block(self, feature, block):
205:         if feature is not self._active_feature:
206:             raise RuntimeError("Inactive feature attempted to submit commands")
207:         if self.busy:
208:             raise RuntimeError("Cannot replace an active command block")
209:         commands = tuple(flatten_commands(block))
210:         self._active_commands = commands
211:         self._pending = deque(commands)
212:         self._block_prompt_context = self._prompt_context
213:         self._recovery_retries = {}
214:         self._replay_context_target = None
215:         self._context_reset_attempted = False
216: 
217:     def feature_complete(self, feature):
218:         if feature is not self._active_feature:
219:             return
220:         if self.busy:
221:             raise RuntimeError("Feature completed while commands are still pending")
222:         feature.mark_completed()
223:         if feature.completion_message:
224:             self._completed_messages.append(feature.completion_message)
225:         self._finish_standard_output_context(feature)
226:         self._schedule_feature_cleanup(feature, "completion")
227:         self._active_feature = None
228:         self._active_commands = ()
229:         if not self._cleanup:
230:             self._activate_next_feature()
231: 
232:     def register_cleanup(self, feature, action):
233:         if not isinstance(action, CleanupAction):
234:             raise TypeError("cleanup must be a CleanupAction")
235:         self._cleanup_actions.setdefault(feature, []).append(action)
236: 
237:     def with_standard_output(self, feature, callback):
238:         """Run a feature callback after standard console output is available."""
239:         if feature is not self._active_feature:
240:             raise RuntimeError("Inactive feature requested standard console output")
241:         if self.busy or self._standard_output_context:
242:             raise RuntimeError("Cannot start a standard console output context while busy")
243:         self._standard_output_context = _StandardOutputContext(feature, callback)
244:         self.submit_block(feature, CommandSequence("console-output-inspect", [
245:             CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),
246:         ]))
247: 
248:     def _schedule_feature_cleanup(self, feature, trigger):
249:         actions = self._cleanup_actions.pop(feature, [])
250:         for action in actions:
251:             if (trigger == "completion" and action.on_completion) or (
252:                 trigger == "interruption" and action.on_interruption
253:             ):
254:                 self.logger.debug(f"Scheduling cleanup {action.name} after {trigger}")
255:                 self._cleanup.extend(action.block.flatten())
256: 
257:     def on_output(self, output):
258:         if not isinstance(output, Data):
259:             raise TypeError("commander output must be terminal.Data")
260:         if not output:
261:             return output
262:         if self._inflight:
263:             if self._call_feature(self._inflight.on_output, output):
264:                 return output
265:             if self._active_feature and self._call_feature(self._active_feature.on_output, output):
266:                 return output
267:         self._inspect_output(output)
268:         return output
269: 
270:     def on_state(self, state, output):
271:         """Called by the driver for every recognized serial state."""
272:         self._current_state = state
273:         self._callback_failed = False
274:         if state == FOSCliState.CMD_PROMPT:
275:             context = self._extract_prompt_context(output)
276:             if context is not None:
277:                 self._prompt_context = context
278:             # Some releases return directly to a usable prompt after login,
279:             # without a Welcome banner. The prompt also ends session recovery.
280:             self._authenticated_once = True
281:             self._recovering = False
282:         if self._pending_feature_error is not None:
283:             if state == FOSCliState.CMD_PROMPT:
284:                 self._recover_feature_error()
285:             elif state == FOSCliState.SESSION_LOST:
286:                 self._session_epoch += 1
287:                 self._recovering = True
288:             elif state == FOSCliState.CREDENTIAL_ACCEPTED:
289:                 self._authenticated_once = True
290:                 self._recovering = False
291:             return
292:         self.on_output(output)
293:         if self._callback_failed:
294:             if state == FOSCliState.CMD_PROMPT:
295:                 self._recover_feature_error()
296:             return
297:         if self._pending_feature_error is not None:
298:             if state == FOSCliState.CMD_PROMPT:
299:                 self._recover_feature_error()
300:             return
301: 
302:         if state == FOSCliState.SESSION_LOST:
303:             self._handle_session_loss()
304:             return
305:         if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:
306:             # Password updates can return to login without the explicit
307:             # SESSION_LOST banner. Requeue the active command block so it is
308:             # applied after the driver restores an accepted login.
309:             self._handle_session_loss()
310:             return
311:         if state == FOSCliState.CREDENTIAL_ACCEPTED:
312:             self._authenticated_once = True
313:             self._recovering = False
314:             return
315:         if self._inflight and state in (
316:             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)
317:         ):
318:             self._complete_inflight(state)
319:             return
320: 
321:         if state == FOSCliState.CMD_PROMPT and not self._recovering:
322:             self._dispatch_next()
323:         if self._callback_failed and state == FOSCliState.CMD_PROMPT:
324:             self._recover_feature_error()
325: 
326:     def on_prompt_echo(self, output):
327:         """Handle a prompt line that had trailing text after the prompt token."""
328:         if self.on_output(output).discarded:
329:             return
330:         self.logger.debug("Prompt had unexpected trailing output; requesting a clean prompt")
331:         self.terminal.write(b"\r")
332: 
333:     def _inspect_output(self, output):
334:         if self._recovering:
335:             output.discard()
336: 
337:     def on_idle_prompt(self):
338:         """Recover errors or dispatch work while idle at a known prompt."""
339:         if self._inflight or self._recovering:
340:             return
341:         if self._pending_feature_error is not None:
342:             # The driver calls this after a read timeout at a known CLI prompt.
343:             # on_state has since recorded TN_TIMEOUT, so recover explicitly.
344:             self._recover_feature_error(at_idle_prompt=True)
345:             return
346:         if self._pending or self._cleanup or self._active_feature is None:
347:             self._dispatch_next()
348: 
349:     def _activate_next_feature(self):
350:         if self._ready or self._active_feature or self._recovering:
351:             return
352:         if not self._features:
353:             if self._cleanup:
354:                 return
355:             self._ready = True
356:             self.terminal.close()
357:             if not self._startup_complete:
358:                 self._startup_complete = True
359:                 elapsed = datetime.datetime.now() - self._start_time
360:                 if self._feature_errors:

(Showing lines 1-360 of 687. Use offset=361 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d8de20001jHmbOIYsygGhSV",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d779d0001Wet13sBNqG25UI",
  "callID": "call_d4075642a8ca4734b96495fa",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_commander.py",
      "limit": 360
    },
    "output": "<path>/source/head/fortinet/common/fos_commander.py</path>\n<type>file</type>\n<content>\n1: \"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n2: \n3: import datetime\n4: import re\n5: from collections import deque\n6: from contextlib import ExitStack\n7: from dataclasses import dataclass\n8: \n9: from .cli_commands import (\n10:     CleanupAction,\n11:     CommandAttempt,\n12:     CommandSequence,\n13:     CommandSpec,\n14:     ConfigBlock,\n15:     ContextLossAction,\n16:     SessionLossAction,\n17:     flatten_commands,\n18: )\n19: from .terminal import Data\n20: from .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n21: \n22: DISPATCHABLE_COMPLETION_STATES = {\n23:     FOSCliState.CMD_PROMPT,\n24:     FOSCliState.CONFIRMATION,\n25:     FOSCliState.MULTILINE_PROMPT,\n26: }\n27: COMMAND_FAILURE_PATTERN = re.compile(\n28:     rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n29: )\n30: CLI_PROMPT_CONTEXT_PATTERN = re.compile(\n31:     rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n32:     + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n33: )\n34: \n35: \n36: @dataclass\n37: class _StandardOutputContext:\n38:     feature: object\n39:     callback: object\n40:     phase: str = \"inspect\"\n41:     restore: bool = False\n42: \n43: \n44: class FOSCommander:\n45:     MAX_COMMAND_RECOVERY_RETRIES = 1\n46:     _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n47:     _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n48:     _CONSOLE_STANDARD_LINE = \"set output standard\"\n49: \n50:     def __init__(self, terminal, logger, continue_on_error=False):\n51:         self.terminal = terminal\n52:         self.logger = logger\n53:         self._features = deque()\n54:         self._active_feature = None\n55:         self._active_commands = ()\n56:         self._pending = deque()\n57:         self._inflight = None\n58:         self._attempt_number = 0\n59:         self._session_epoch = 0\n60:         self._recovering = False\n61:         self._cleanup = deque()\n62:         self._cleanup_actions = {}\n63:         self._in_cleanup = False\n64:         self._standard_output_context = None\n65:         self._suppression = ExitStack()\n66:         self._ready = False\n67:         self._startup_complete = False\n68:         self._feature_errors = []\n69:         self._authenticated_once = False\n70:         self._completed_messages = deque()\n71:         self._start_time = datetime.datetime.now()\n72:         self._continue_on_error = continue_on_error\n73:         self._pending_feature_error = None\n74:         self._current_state = None\n75:         self._callback_failed = False\n76:         self._prompt_context = None\n77:         self._block_prompt_context = None\n78:         self._recovery_retries = {}\n79:         self._cleanup_retries = {}\n80:         self._replay_context_target = None\n81:         self._context_reset_attempted = False\n82:         self._in_context_reset = False\n83: \n84:     def _call_feature(self, callback, *args):\n85:         \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n86:         try:\n87:             return callback(*args)\n88:         except Exception as error:\n89:             self._handle_work_error(error, from_callback=True)\n90:             return None\n91: \n92:     def _handle_work_error(self, error, *, from_callback=False):\n93:         \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n94:         if not self._continue_on_error:\n95:             raise error\n96:         if from_callback:\n97:             self.logger.exception(\"Bootstrap feature callback failed\")\n98:         else:\n99:             self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n100:         self._pending_feature_error = error\n101:         self._callback_failed = True\n102: \n103:     def _recover_feature_error(self, *, at_idle_prompt=False):\n104:         error = self._pending_feature_error\n105:         if error is None or (\n106:             self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n107:         ):\n108:             return False\n109:         failed_work = self.continue_after_error(error, at_command_prompt=True)\n110:         if failed_work is None:\n111:             return False\n112:         self._pending_feature_error = None\n113:         self.logger.error(\n114:             \"Bootstrap work %s failed; continuing with remaining features \"\n115:             \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n116:             failed_work,\n117:         )\n118:         self._dispatch_next()\n119:         return True\n120: \n121:     @property\n122:     def ready(self):\n123:         return self._ready\n124: \n125:     @property\n126:     def busy(self):\n127:         return self._inflight is not None or bool(self._pending) or bool(self._cleanup)\n128: \n129:     @property\n130:     def startup_complete(self):\n131:         \"\"\"Whether the initial feature queue has drained, with or without errors.\"\"\"\n132:         return self._startup_complete\n133: \n134:     @property\n135:     def feature_errors(self):\n136:         \"\"\"Bootstrap feature errors recorded while best-effort mode is active.\"\"\"\n137:         return tuple(self._feature_errors)\n138: \n139:     def continue_after_error(self, error, at_command_prompt):\n140:         \"\"\"Skip failed work only when the CLI is back at a usable prompt.\n141: \n142:         A login rejection after the driver's credential recovery attempts, or\n143:         an error during an interactive prompt, cannot be recovered by sending\n144:         the next feature's commands, so automatic bootstrap must stop.\n145:         \"\"\"\n146:         if not at_command_prompt or self._ready:\n147:             return None\n148:         if self._active_feature is None and not self._in_cleanup:\n149:             return None\n150: \n151:         if self._active_feature is not None:\n152:             failed_name = self._active_feature.name\n153:             self._pending.clear()\n154:             self._active_commands = ()\n155:             self._inflight = None\n156:             self._suppression.close()\n157:             self._suppression = ExitStack()\n158:             self._finish_standard_output_context(self._active_feature)\n159:             self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n160:             self._active_feature = None\n161:         else:\n162:             failed_name = \"cleanup\"\n163:             self._inflight = None\n164:             self._suppression.close()\n165:             self._suppression = ExitStack()\n166: \n167:         self._in_cleanup = False\n168:         self._replay_context_target = None\n169:         self._in_context_reset = False\n170:         self._cleanup_retries.clear()\n171:         self._feature_errors.append((failed_name, str(error)))\n172:         return failed_name\n173: \n174:     def record_feature_error(self, name, error):\n175:         \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n176:         self._feature_errors.append((name, str(error)))\n177:         self.logger.info(\"Using recovery for %s: %s\", name, error)\n178: \n179:     def resolve_feature_error(self, name, resolution):\n180:         \"\"\"Clear a recoverable feature error after its condition is resolved.\"\"\"\n181:         remaining = [\n182:             (feature_name, error)\n183:             for feature_name, error in self._feature_errors\n184:             if feature_name != name\n185:         ]\n186:         resolved_count = len(self._feature_errors) - len(remaining)\n187:         if resolved_count:\n188:             self._feature_errors = remaining\n189:             self.logger.info(\n190:                 \"Resolved %s bootstrap recovery after %s\",\n191:                 name,\n192:                 resolution,\n193:             )\n194: \n195:     def start(self, features):\n196:         self._features.extend(features)\n197: \n198:     def tick(self):\n199:         if self._pending_feature_error is not None:\n200:             return\n201:         if self._active_feature and hasattr(self._active_feature, \"tick\"):\n202:             self._call_feature(self._active_feature.tick)\n203: \n204:     def submit_block(self, feature, block):\n205:         if feature is not self._active_feature:\n206:             raise RuntimeError(\"Inactive feature attempted to submit commands\")\n207:         if self.busy:\n208:             raise RuntimeError(\"Cannot replace an active command block\")\n209:         commands = tuple(flatten_commands(block))\n210:         self._active_commands = commands\n211:         self._pending = deque(commands)\n212:         self._block_prompt_context = self._prompt_context\n213:         self._recovery_retries = {}\n214:         self._replay_context_target = None\n215:         self._context_reset_attempted = False\n216: \n217:     def feature_complete(self, feature):\n218:         if feature is not self._active_feature:\n219:             return\n220:         if self.busy:\n221:             raise RuntimeError(\"Feature completed while commands are still pending\")\n222:         feature.mark_completed()\n223:         if feature.completion_message:\n224:             self._completed_messages.append(feature.completion_message)\n225:         self._finish_standard_output_context(feature)\n226:         self._schedule_feature_cleanup(feature, \"completion\")\n227:         self._active_feature = None\n228:         self._active_commands = ()\n229:         if not self._cleanup:\n230:             self._activate_next_feature()\n231: \n232:     def register_cleanup(self, feature, action):\n233:         if not isinstance(action, CleanupAction):\n234:             raise TypeError(\"cleanup must be a CleanupAction\")\n235:         self._cleanup_actions.setdefault(feature, []).append(action)\n236: \n237:     def with_standard_output(self, feature, callback):\n238:         \"\"\"Run a feature callback after standard console output is available.\"\"\"\n239:         if feature is not self._active_feature:\n240:             raise RuntimeError(\"Inactive feature requested standard console output\")\n241:         if self.busy or self._standard_output_context:\n242:             raise RuntimeError(\"Cannot start a standard console output context while busy\")\n243:         self._standard_output_context = _StandardOutputContext(feature, callback)\n244:         self.submit_block(feature, CommandSequence(\"console-output-inspect\", [\n245:             CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),\n246:         ]))\n247: \n248:     def _schedule_feature_cleanup(self, feature, trigger):\n249:         actions = self._cleanup_actions.pop(feature, [])\n250:         for action in actions:\n251:             if (trigger == \"completion\" and action.on_completion) or (\n252:                 trigger == \"interruption\" and action.on_interruption\n253:             ):\n254:                 self.logger.debug(f\"Scheduling cleanup {action.name} after {trigger}\")\n255:                 self._cleanup.extend(action.block.flatten())\n256: \n257:     def on_output(self, output):\n258:         if not isinstance(output, Data):\n259:             raise TypeError(\"commander output must be terminal.Data\")\n260:         if not output:\n261:             return output\n262:         if self._inflight:\n263:             if self._call_feature(self._inflight.on_output, output):\n264:                 return output\n265:             if self._active_feature and self._call_feature(self._active_feature.on_output, output):\n266:                 return output\n267:         self._inspect_output(output)\n268:         return output\n269: \n270:     def on_state(self, state, output):\n271:         \"\"\"Called by the driver for every recognized serial state.\"\"\"\n272:         self._current_state = state\n273:         self._callback_failed = False\n274:         if state == FOSCliState.CMD_PROMPT:\n275:             context = self._extract_prompt_context(output)\n276:             if context is not None:\n277:                 self._prompt_context = context\n278:             # Some releases return directly to a usable prompt after login,\n279:             # without a Welcome banner. The prompt also ends session recovery.\n280:             self._authenticated_once = True\n281:             self._recovering = False\n282:         if self._pending_feature_error is not None:\n283:             if state == FOSCliState.CMD_PROMPT:\n284:                 self._recover_feature_error()\n285:             elif state == FOSCliState.SESSION_LOST:\n286:                 self._session_epoch += 1\n287:                 self._recovering = True\n288:             elif state == FOSCliState.CREDENTIAL_ACCEPTED:\n289:                 self._authenticated_once = True\n290:                 self._recovering = False\n291:             return\n292:         self.on_output(output)\n293:         if self._callback_failed:\n294:             if state == FOSCliState.CMD_PROMPT:\n295:                 self._recover_feature_error()\n296:             return\n297:         if self._pending_feature_error is not None:\n298:             if state == FOSCliState.CMD_PROMPT:\n299:                 self._recover_feature_error()\n300:             return\n301: \n302:         if state == FOSCliState.SESSION_LOST:\n303:             self._handle_session_loss()\n304:             return\n305:         if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:\n306:             # Password updates can return to login without the explicit\n307:             # SESSION_LOST banner. Requeue the active command block so it is\n308:             # applied after the driver restores an accepted login.\n309:             self._handle_session_loss()\n310:             return\n311:         if state == FOSCliState.CREDENTIAL_ACCEPTED:\n312:             self._authenticated_once = True\n313:             self._recovering = False\n314:             return\n315:         if self._inflight and state in (\n316:             self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n317:         ):\n318:             self._complete_inflight(state)\n319:             return\n320: \n321:         if state == FOSCliState.CMD_PROMPT and not self._recovering:\n322:             self._dispatch_next()\n323:         if self._callback_failed and state == FOSCliState.CMD_PROMPT:\n324:             self._recover_feature_error()\n325: \n326:     def on_prompt_echo(self, output):\n327:         \"\"\"Handle a prompt line that had trailing text after the prompt token.\"\"\"\n328:         if self.on_output(output).discarded:\n329:             return\n330:         self.logger.debug(\"Prompt had unexpected trailing output; requesting a clean prompt\")\n331:         self.terminal.write(b\"\\r\")\n332: \n333:     def _inspect_output(self, output):\n334:         if self._recovering:\n335:             output.discard()\n336: \n337:     def on_idle_prompt(self):\n338:         \"\"\"Recover errors or dispatch work while idle at a known prompt.\"\"\"\n339:         if self._inflight or self._recovering:\n340:             return\n341:         if self._pending_feature_error is not None:\n342:             # The driver calls this after a read timeout at a known CLI prompt.\n343:             # on_state has since recorded TN_TIMEOUT, so recover explicitly.\n344:             self._recover_feature_error(at_idle_prompt=True)\n345:             return\n346:         if self._pending or self._cleanup or self._active_feature is None:\n347:             self._dispatch_next()\n348: \n349:     def _activate_next_feature(self):\n350:         if self._ready or self._active_feature or self._recovering:\n351:             return\n352:         if not self._features:\n353:             if self._cleanup:\n354:                 return\n355:             self._ready = True\n356:             self.terminal.close()\n357:             if not self._startup_complete:\n358:                 self._startup_complete = True\n359:                 elapsed = datetime.datetime.now() - self._start_time\n360:                 if self._feature_errors:\n\n(Showing lines 1-360 of 687. Use offset=361 to continue.)\n</content>",
    "title": "source/head/fortinet/common/fos_commander.py",
    "metadata": {
      "preview": "\"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n\nimport datetime\nimport re\nfrom collections import deque\nfrom contextlib import ExitStack\nfrom dataclasses import dataclass\n\nfrom .cli_commands import (\n    CleanupAction,\n    CommandAttempt,\n    CommandSequence,\n    CommandSpec,\n    ConfigBlock,\n    ContextLossAction,\n    SessionLossAction,\n    flatten_commands,\n)\nfrom .terminal import Data\nfrom .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_commander.py",
        "text": "\"\"\"Event-driven command scheduler for the FortiOS CLI.\"\"\"\n\nimport datetime\nimport re\nfrom collections import deque\nfrom contextlib import ExitStack\nfrom dataclasses import dataclass\n\nfrom .cli_commands import (\n    CleanupAction,\n    CommandAttempt,\n    CommandSequence,\n    CommandSpec,\n    ConfigBlock,\n    ContextLossAction,\n    SessionLossAction,\n    flatten_commands,\n)\nfrom .terminal import Data\nfrom .common import BOOTSTRAP_HOSTNAME_REGEX, FOSCliState, TRACE_LEVEL\n\nDISPATCHABLE_COMPLETION_STATES = {\n    FOSCliState.CMD_PROMPT,\n    FOSCliState.CONFIRMATION,\n    FOSCliState.MULTILINE_PROMPT,\n}\nCOMMAND_FAILURE_PATTERN = re.compile(\n    rb\"(?mi)^\\s*Command fail\\.\\s*Return code\\s+(-?\\d+)\"\n)\nCLI_PROMPT_CONTEXT_PATTERN = re.compile(\n    rb\"(?m)^[ \\t]*\" + BOOTSTRAP_HOSTNAME_REGEX\n    + rb\"(?P<context>(?:[ \\t]+\\([^)]+\\))*)[ \\t]*[#$][ \\t]*\\r?$\"\n)\n\n\n@dataclass\nclass _StandardOutputContext:\n    feature: object\n    callback: object\n    phase: str = \"inspect\"\n    restore: bool = False\n\n\nclass FOSCommander:\n    MAX_COMMAND_RECOVERY_RETRIES = 1\n    _CONSOLE_OUTPUT_PATTERN = re.compile(rb\"(?mi)^\\s*set output (more|standard)\\s*\\r?$\")\n    _CONSOLE_INSPECT_LINE = \"show full-configuration system console\"\n    _CONSOLE_STANDARD_LINE = \"set output standard\"\n\n    def __init__(self, terminal, logger, continue_on_error=False):\n        self.terminal = terminal\n        self.logger = logger\n        self._features = deque()\n        self._active_feature = None\n        self._active_commands = ()\n        self._pending = deque()\n        self._inflight = None\n        self._attempt_number = 0\n        self._session_epoch = 0\n        self._recovering = False\n        self._cleanup = deque()\n        self._cleanup_actions = {}\n        self._in_cleanup = False\n        self._standard_output_context = None\n        self._suppression = ExitStack()\n        self._ready = False\n        self._startup_complete = False\n        self._feature_errors = []\n        self._authenticated_once = False\n        self._completed_messages = deque()\n        self._start_time = datetime.datetime.now()\n        self._continue_on_error = continue_on_error\n        self._pending_feature_error = None\n        self._current_state = None\n        self._callback_failed = False\n        self._prompt_context = None\n        self._block_prompt_context = None\n        self._recovery_retries = {}\n        self._cleanup_retries = {}\n        self._replay_context_target = None\n        self._context_reset_attempted = False\n        self._in_context_reset = False\n\n    def _call_feature(self, callback, *args):\n        \"\"\"Run a feature callback and apply best-effort policy at this boundary.\"\"\"\n        try:\n            return callback(*args)\n        except Exception as error:\n            self._handle_work_error(error, from_callback=True)\n            return None\n\n    def _handle_work_error(self, error, *, from_callback=False):\n        \"\"\"Apply the configured failure policy after feature/recovery decisions.\"\"\"\n        if not self._continue_on_error:\n            raise error\n        if from_callback:\n            self.logger.exception(\"Bootstrap feature callback failed\")\n        else:\n            self.logger.error(\"Bootstrap work failed: %s\", error, exc_info=error)\n        self._pending_feature_error = error\n        self._callback_failed = True\n\n    def _recover_feature_error(self, *, at_idle_prompt=False):\n        error = self._pending_feature_error\n        if error is None or (\n            self._current_state != FOSCliState.CMD_PROMPT and not at_idle_prompt\n        ):\n            return False\n        failed_work = self.continue_after_error(error, at_command_prompt=True)\n        if failed_work is None:\n            return False\n        self._pending_feature_error = None\n        self.logger.error(\n            \"Bootstrap work %s failed; continuing with remaining features \"\n            \"because FOS_EXIT_ON_BOOTSTRAP_ERROR=false\",\n            failed_work,\n        )\n        self._dispatch_next()\n        return True\n\n    @property\n    def ready(self):\n        return self._ready\n\n    @property\n    def busy(self):\n        return self._inflight is not None or bool(self._pending) or bool(self._cleanup)\n\n    @property\n    def startup_complete(self):\n        \"\"\"Whether the initial feature queue has drained, with or without errors.\"\"\"\n        return self._startup_complete\n\n    @property\n    def feature_errors(self):\n        \"\"\"Bootstrap feature errors recorded while best-effort mode is active.\"\"\"\n        return tuple(self._feature_errors)\n\n    def continue_after_error(self, error, at_command_prompt):\n        \"\"\"Skip failed work only when the CLI is back at a usable prompt.\n\n        A login rejection after the driver's credential recovery attempts, or\n        an error during an interactive prompt, cannot be recovered by sending\n        the next feature's commands, so automatic bootstrap must stop.\n        \"\"\"\n        if not at_command_prompt or self._ready:\n            return None\n        if self._active_feature is None and not self._in_cleanup:\n            return None\n\n        if self._active_feature is not None:\n            failed_name = self._active_feature.name\n            self._pending.clear()\n            self._active_commands = ()\n            self._inflight = None\n            self._suppression.close()\n            self._suppression = ExitStack()\n            self._finish_standard_output_context(self._active_feature)\n            self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n            self._active_feature = None\n        else:\n            failed_name = \"cleanup\"\n            self._inflight = None\n            self._suppression.close()\n            self._suppression = ExitStack()\n\n        self._in_cleanup = False\n        self._replay_context_target = None\n        self._in_context_reset = False\n        self._cleanup_retries.clear()\n        self._feature_errors.append((failed_name, str(error)))\n        return failed_name\n\n    def record_feature_error(self, name, error):\n        \"\"\"Record a recoverable bootstrap problem without stopping the queue.\"\"\"\n        self._feature_errors.append((name, str(error)))\n        self.logger.info(\"Using recovery for %s: %s\", name, error)\n\n    def resolve_feature_error(self, name, resolution):\n        \"\"\"Clear a recoverable feature error after its condition is resolved.\"\"\"\n        remaining = [\n            (feature_name, error)\n            for feature_name, error in self._feature_errors\n            if feature_name != name\n        ]\n        resolved_count = len(self._feature_errors) - len(remaining)\n        if resolved_count:\n            self._feature_errors = remaining\n            self.logger.info(\n                \"Resolved %s bootstrap recovery after %s\",\n                name,\n                resolution,\n            )\n\n    def start(self, features):\n        self._features.extend(features)\n\n    def tick(self):\n        if self._pending_feature_error is not None:\n            return\n        if self._active_feature and hasattr(self._active_feature, \"tick\"):\n            self._call_feature(self._active_feature.tick)\n\n    def submit_block(self, feature, block):\n        if feature is not self._active_feature:\n            raise RuntimeError(\"Inactive feature attempted to submit commands\")\n        if self.busy:\n            raise RuntimeError(\"Cannot replace an active command block\")\n        commands = tuple(flatten_commands(block))\n        self._active_commands = commands\n        self._pending = deque(commands)\n        self._block_prompt_context = self._prompt_context\n        self._recovery_retries = {}\n        self._replay_context_target = None\n        self._context_reset_attempted = False\n\n    def feature_complete(self, feature):\n        if feature is not self._active_feature:\n            return\n        if self.busy:\n            raise RuntimeError(\"Feature completed while commands are still pending\")\n        feature.mark_completed()\n        if feature.completion_message:\n            self._completed_messages.append(feature.completion_message)\n        self._finish_standard_output_context(feature)\n        self._schedule_feature_cleanup(feature, \"completion\")\n        self._active_feature = None\n        self._active_commands = ()\n        if not self._cleanup:\n            self._activate_next_feature()\n\n    def register_cleanup(self, feature, action):\n        if not isinstance(action, CleanupAction):\n            raise TypeError(\"cleanup must be a CleanupAction\")\n        self._cleanup_actions.setdefault(feature, []).append(action)\n\n    def with_standard_output(self, feature, callback):\n        \"\"\"Run a feature callback after standard console output is available.\"\"\"\n        if feature is not self._active_feature:\n            raise RuntimeError(\"Inactive feature requested standard console output\")\n        if self.busy or self._standard_output_context:\n            raise RuntimeError(\"Cannot start a standard console output context while busy\")\n        self._standard_output_context = _StandardOutputContext(feature, callback)\n        self.submit_block(feature, CommandSequence(\"console-output-inspect\", [\n            CommandSpec(self._CONSOLE_INSPECT_LINE, capture_output=True, suppress_output=True),\n        ]))\n\n    def _schedule_feature_cleanup(self, feature, trigger):\n        actions = self._cleanup_actions.pop(feature, [])\n        for action in actions:\n            if (trigger == \"completion\" and action.on_completion) or (\n                trigger == \"interruption\" and action.on_interruption\n            ):\n                self.logger.debug(f\"Scheduling cleanup {action.name} after {trigger}\")\n                self._cleanup.extend(action.block.flatten())\n\n    def on_output(self, output):\n        if not isinstance(output, Data):\n            raise TypeError(\"commander output must be terminal.Data\")\n        if not output:\n            return output\n        if self._inflight:\n            if self._call_feature(self._inflight.on_output, output):\n                return output\n            if self._active_feature and self._call_feature(self._active_feature.on_output, output):\n                return output\n        self._inspect_output(output)\n        return output\n\n    def on_state(self, state, output):\n        \"\"\"Called by the driver for every recognized serial state.\"\"\"\n        self._current_state = state\n        self._callback_failed = False\n        if state == FOSCliState.CMD_PROMPT:\n            context = self._extract_prompt_context(output)\n            if context is not None:\n                self._prompt_context = context\n            # Some releases return directly to a usable prompt after login,\n            # without a Welcome banner. The prompt also ends session recovery.\n            self._authenticated_once = True\n            self._recovering = False\n        if self._pending_feature_error is not None:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            elif state == FOSCliState.SESSION_LOST:\n                self._session_epoch += 1\n                self._recovering = True\n            elif state == FOSCliState.CREDENTIAL_ACCEPTED:\n                self._authenticated_once = True\n                self._recovering = False\n            return\n        self.on_output(output)\n        if self._callback_failed:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            return\n        if self._pending_feature_error is not None:\n            if state == FOSCliState.CMD_PROMPT:\n                self._recover_feature_error()\n            return\n\n        if state == FOSCliState.SESSION_LOST:\n            self._handle_session_loss()\n            return\n        if state == FOSCliState.PROVIDE_USERNAME and self._authenticated_once:\n            # Password updates can return to login without the explicit\n            # SESSION_LOST banner. Requeue the active command block so it is\n            # applied after the driver restores an accepted login.\n            self._handle_session_loss()\n            return\n        if state == FOSCliState.CREDENTIAL_ACCEPTED:\n            self._authenticated_once = True\n            self._recovering = False\n            return\n        if self._inflight and state in (\n            self._inflight.spec.completion_states or (FOSCliState.CMD_PROMPT,)\n        ):\n            self._complete_inflight(state)\n            return\n\n        if state == FOSCliState.CMD_PROMPT and not self._recovering:\n            self._dispatch_next()\n        if self._callback_failed and state == FOSCliState.CMD_PROMPT:\n            self._recover_feature_error()\n\n    def on_prompt_echo(self, output):\n        \"\"\"Handle a prompt line that had trailing text after the prompt token.\"\"\"\n        if self.on_output(output).discarded:\n            return\n        self.logger.debug(\"Prompt had unexpected trailing output; requesting a clean prompt\")\n        self.terminal.write(b\"\\r\")\n\n    def _inspect_output(self, output):\n        if self._recovering:\n            output.discard()\n\n    def on_idle_prompt(self):\n        \"\"\"Recover errors or dispatch work while idle at a known prompt.\"\"\"\n        if self._inflight or self._recovering:\n            return\n        if self._pending_feature_error is not None:\n            # The driver calls this after a read timeout at a known CLI prompt.\n            # on_state has since recorded TN_TIMEOUT, so recover explicitly.\n            self._recover_feature_error(at_idle_prompt=True)\n            return\n        if self._pending or self._cleanup or self._active_feature is None:\n            self._dispatch_next()\n\n    def _activate_next_feature(self):\n        if self._ready or self._active_feature or self._recovering:\n            return\n        if not self._features:\n            if self._cleanup:\n                return\n            self._ready = True\n            self.terminal.close()\n            if not self._startup_complete:\n                self._startup_complete = True\n                elapsed = datetime.datetime.now() - self._start_time\n                if self._feature_errors:",
        "lineStart": 1,
        "lineEnd": 360,
        "totalLines": 687,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716706853,
      "end": 1793716706861
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d8de30001W546bbM6wfAniQ",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d779d0001Wet13sBNqG25UI",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 106362,
    "input": 14006,
    "output": 55,
    "reasoning": 10893,
    "cache": {
      "read": 81408,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d779d0001Wet13sBNqG25UI",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716615632,
    "completed": 1793716706866
  },
  "parentID": "msg_1a1d645d70013gv2VsgIPALXxn",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 106362,
    "input": 14006,
    "output": 55,
    "reasoning": 10893,
    "cache": {
      "read": 81408,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 35
compaction
{
  "type": "compaction",
  "id": "prt_1a1d8de34001LAftviP2F3ERiE",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d8de33001pET7RWke6yehD9",
  "auto": true,
  "overflow": false
}
Message metadata
{
  "role": "user",
  "id": "msg_1a1d8de33001pET7RWke6yehD9",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716706867
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 36
step-start
{
  "type": "step-start",
  "id": "prt_1a1d8e98c001nFwtOw4mElXHd0",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d8de4a0013MLZ4yeLcsV2WF"
}
Reasoning
Let me construct the updated summary. The conversation shows significant progress: all source files fully read, all tests read, READMEs read, full diff re-read with exact offsets. Corrections to prior summary: fos_commander.py is 687 lines (fully read, offset 700 out of range), common.py is 92 lines (fully read), test_common_terminal_driver.py is 332 lines (fully read). Remaining: final analysis/finalize findings and emit trusted result schema.

Key new facts from conversation:
- startup_config.py full read: filter_startup_config_blocks (pre-existing, diff confirms), _startup_config_commands quote parser.
- env.py full read (48 lines): _candidate_names order = aliases → FTNT spelling → original → legacy_aliases.
- fos_commander.py head lines 1-360 re-read: CLI_PROMPT_CONTEXT_PATTERN at lines 30-33, MAX_COMMAND_RECOVERY_RETRIES=1.
- cli_commands.py: CommandSpec fully read (207 lines total, lines 1-100 seen).
- launch.py lines 61+ read (parse_log_level, exit_on_bootstrap_error, container_dns_servers).
- features/license.py full-ish read: LICENSE_FAILURE_PATTERN, SetLicense phases.
- features/credentials.py: exit spec in admin-relogin block with expected_completion_state=PROVIDE_USERNAME.
- features/pki.py: comment-only change; docstring; env vars.
- Tests all read (boundaries, parsing, admin_credentials, recovery, scope_errors, terminal_driver — 332 lines).
- READMEs read (both).
- diff.txt read fully (offsets 1-450, 451-1121, 1121-end): startup_config diff = only _startup_config_commands added, filter pre-existing; README.md diff = only startup config paragraph; docker README new "Scope-closing commands" paragraph says `FOS_EXIT_ON_BOOTSTRAP_ERROR=false` while line 311 says `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` — doc inconsistency finding (P4 candidate).
- Analysis findings candidates: only P4-level (state_case duplicated completion assignment in test_common_stack_boundaries.py; FOS_ vs FTNT_ doc inconsistency in docker README). No P1/P2 findings found.
- fos_commander.py on_state flow verified: context extraction before dispatch; CREDENTIAL_ACCEPTED handling; _complete_inflight then dispatch.

Next move: finalize findings list, optionally re-read remaining fos_commander.py portions (360-687) for precise anchors, then emit trusted result schema with disclosure of no test execution and manifest incomplete: true.
## Objective
- Perform a source-only, read-only PR review of the snapshot at `/source` (repo `srl-labs/vrnetlab`, head `1c29a33a37619b7547248e3b845130ba1f5f8ad0`, base `11dd16f88e2e5990de1061be498577af6c5d3552`), covering all 18 changed paths from `diff.txt`, then emit the trusted result schema (disclosing tests not executed; manifest indicates snapshot incomplete: true → report incomplete coverage).

## Important Details
- `standards.json` is empty (`[]`) — no rules to apply.
- 18 changed paths: M `fortinet/common/cli_commands.py`, `common.py`, `features/base.py`, `features/credentials.py`, `features/pki.py`, `features/startup_config.py`, `fos_cli_driver.py`, `fos_commander.py`, `launch.py`, `terminal.py`, `fortigate/README.md`, `fortigate/docker/README.md`, `tests/test_common_stack_boundaries.py`, `tests/test_common_stack_parsing.py`, `tests/test_common_terminal_driver.py`; A `tests/test_common_admin_credentials.py`, `tests/test_common_recovery.py`, `tests/test_common_scope_errors.py`.
- Read tool: bare `/source` directory read denied; must read specific files; batch independent calls. diff.txt file offsets: cli_commands=1, common=186, features/base=217, credentials=236, pki=301, startup_config=323, fos_cli_driver=387, fos_commander=449, launch=861, terminal=892, README.md=983, docker/README=1004, admin_credentials=1117, recovery=1277, scope_errors=1575, stack_boundaries=1735, stack_parsing=1821, terminal_driver=1948.
- Corrected file sizes (prior summary's "truncated at N lines" was misleading — files are fully read): `fos_commander.py` 687 lines (fully read, re-read lines 1–360 recently), `common.py` 92 lines, `test_common_terminal_driver.py` 332 lines, `cli_commands.py` 207 lines, `env.py` 48 lines.
- PR theme: FortiOS CLI stack rework — `ContextLossAction` (RESTART_BLOCK/FAIL), `CommandSpec.context_loss`/`continuation`, prompt-context tracking (`CLI_PROMPT_CONTEXT_PATTERN` at `fos_commander.py:30-33`, `BOOTSTRAP_HOSTNAME_REGEX` (bytes literal, GENERIC|DEFAULT|LICENSED alternation), `PROMPT_CONTEXT_REGEX = rb"(?:[ \t]+\([^)]+\))*"`), scope-commit failure detection for `closes_scope` ("next"/"end" always capture; "Command fail. Return code -N" always fatal), abort-based context restore, `_recovery_retries` keyed by block_index, `_cleanup_retries` keyed by `id(spec)`, terminal `Data` timeout exposes FULL retained buffer (with `received_new_data` flag), env aliasing FTNT_*/FOS_*, `TRACE_LEVEL`(=9) logging change, `KernelPanicError` handling.
- env.py `_candidate_names` order verified: aliases → FTNT spelling (if FOS_-prefixed) → original name → legacy_aliases. `has_env`/`get_env` follow same order.
- Verified analysis conclusions (no P1/P2 defects found):
  - Driver `process_state`/`_next_state`: unmatched output forwarded to `commander.on_output` once, then replaced with empty `Data`; matched output reaches commander via `on_state` → `on_output`; each byte enters `attempt.output` at most once. `TN_TIMEOUT` gets empty output after full-buffer inspection (intended change).
  - Context change after `next`/`end` exempted via `_command_may_change_context` (includes "config "/"edit ", {"next","end","abort","exit","quit"}, "set vdom-mode multi-vdom"; continuation lines exempt→context change is loss); falls through to `_validate_completion` → closes_scope failure always checked (test covers context change to "interface").
  - `_on_session_loss`: `_in_context_reset` check returns early (bounded abort after reconnect); `_in_cleanup` path appends left with `_cleanup_retries`; then `_schedule_feature_cleanup(active, "interruption")` + feature `on_session_loss`.
  - `_restart_active_block` replays via `_replay_context_target = self._block_prompt_context`; `_block_prompt_context` is set at `submit_block` after context extraction (non-None for feature blocks); None target is benign (proceed immediately).
  - `on_state` order: context extraction (CMD_PROMPT) → `_recover_feature_error` → session-lost handling → `_complete_inflight` → dispatch; CMD_PROMPT sets `_authenticated_once` at top; CREDENTIAL_ACCEPTED sets it and returns.
  - `fos_commander.py:45 MAX_COMMAND_RECOVERY_RETRIES = 1`.
  - `_flatten_quoted_lines`: all lines `capture_output=True`; last line `expected_completion_state=CMD_PROMPT` when `validate_prompt`; `continuation = index > 0` (so multi-line last lines are continuation → not closes_scope; SetValue defaults `fail_on_error=True` so failures still detected; plain-string multi-line last-line failures surface via enclosing next/end or are invalid usage). `SetValue`/`splitlines()`/text-mode reads ensure `CommandSpec.__post_init__` "\r"/"\n" ValueError not triggerable from normal paths; `startup-config.cfg` parsing uses `removesuffix("\n")`, quote/escape/continuation state traced correct (trailing `\` = line continuation; quote state persists across lines; blank/comment lines inside quotes preserved).
  - credentials.py: `exit` spec in `admin-relogin` block, `expected_completion_state=FOSCliState.PROVIDE_USERNAME`, `session_loss=CONTINUE` (context_loss defaults FAIL); `on_command_dispatched` activates desired credentials BEFORE exit is sent (login answered with desired creds); `_activate_desired_credentials` idempotent via `_desired_credentials_activated`; session-loss CONTINUE on exit → `_pending.clear()` → reconnect → block complete → `on_complete` → activate.
  - license.py (`SetLicense`, `WaitForLicenseValidation`): `on_command_executed` is per-feature (not broadcast) — no cross-feature misfire; `LICENSE_FAILURE_PATTERN = re.compile(rb"(?mi)license install failed")`; `on_output` search is idempotent (no discard needed). license.py is NOT in the changed file list (context only).
  - pki.py change is comment/docstring-only; TFTP fallback only triggers on successful scope close (commander always validates next/end) — by design.
  - startup_config diff = only `_startup_config_commands` added (parse loop refactor); `filter_startup_config_blocks` pre-existing → README `FTNT_FORTIGUARD_HOOKS` env-table omission is pre-existing, not PR-introduced.
  - terminal.py diff touches `Data`/`expect`/`_discard_prefix` only; reader/writer thread logic (`_ensure_reader`, `_read_forever`, `_ByteQueue`) pre-existing. `stable_match = re.search(regex, consumed)` after `del buffer[:match.end()]` is defensive re-run — negligible cost, no bug. `_ByteQueue` put/get/close semantics verified sound; buffer limit bounds regex re-scan cost (1 MiB cap) — no perf finding.
  - `fos_cli_driver.set_prompt_patterns`: `re.escape(name_pattern.encode())` only for str; `BOOTSTRAP_HOSTNAME_REGEX` bytes pattern passes through unchanged (correct).
  - launch.py: `KernelPanicError` caught before generic `Exception` in `bootstrap_spin` (stop + raise); env names resolve via aliases (`FTNT_DISK_SPECS`, `FTNT_LOG_LEVEL`, `FTNT_EXIT_ON_BOOTSTRAP_ERROR`, `FTNT_DNS_PROTOCOL`).
  - Kernel panic flow: `process_state` calls `commander.on_state(KERNEL_PANIC, Data)` before `_handle_state` raises — matches `test_kernel_panic_requires_kernel_diagnostic_and_raises`.
- Potential findings so far (all minor):
  - P4 candidate: docker/README.md new "Scope-closing commands" paragraph says `FOS_EXIT_ON_BOOTSTRAP_ERROR=false` while line ~311 of same doc says `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` — inconsistent env-name spelling in doc introduced by this PR (both spellings functionally accepted via env.py aliases; documented public interface is FTNT_).
  - P4 candidate: `test_common_stack_boundaries.py` `state_case` has duplicated `completion = (FOSCliState.CMD_PROMPT,)` in two adjacent if branches (lines ~105-108) — mergeable simplification.
- Prior resolved concerns (keep for reference): duplicate timeout-Data consumption (resolved), None replay-target (benign), `id(spec)`-keyed `_cleanup_retries` (bounded, at most P4), context-loss-before-validation ordering (resolved), `_recover_feature_error` discarding inflight created without write (acceptable), `on_prompt_echo` matched Data no discard → writes `b"\r"` (by design).

## Work State
### Completed
- Read `/source/standards.json` (empty), `/source/manifest.json`, and FULL `/source/diff.txt` (offsets 1, 451, 1121) — all 18 hunks reviewed; change attribution established for every file (startup_config filter and README env-table gaps are pre-existing).
- FULLY read all 18 head files: `cli_commands.py` (207), `common.py` (92), `env.py` (48), `terminal.py`, `fos_commander.py` (687; re-read lines 1–360 for anchors), `fos_cli_driver.py`, `launch.py`, `features/{base,credentials,license,startup_config,pki}.py`, both READMEs (`fortigate/README.md`, `fortigate/docker/README.md`), and ALL six test files (`test_common_stack_parsing.py`, `test_common_stack_boundaries.py`, `test_common_terminal_driver.py` (332), `test_common_admin_credentials.py`, `test_common_recovery.py`, `test_common_scope_errors.py`).
- Traced and resolved all previously-flagged correctness concerns; verified env aliasing, TRACE_LEVEL logging fix, kernel-panic ordering, startup-config quote parser, credentials relogin flow, PKI fallback design, session/context-loss recovery paths.
- Test coverage assessed as strong for the new behaviors (abort recovery via serial driver, failed `next`, retained-newline idle read, kernel panic, FTNT_ env aliasing, admin credential relogin, session-loss-during-context-reset).

### Active
- Finalizing the findings list (currently only two P4 candidates: docker README `FOS_` vs `FTNT_` env-name inconsistency; duplicated `completion = (FOSCliState.CMD_PROMPT,)` branch in `state_case`).
- Optionally re-read `fos_commander.py` lines ~360–687 to refresh exact content/anchors before writing the report (lines 1–360 are fresh in context).

### Blocked
- (none)

## Next Move
1. Optionally re-read `fos_commander.py` offset 360 (through 687) to refresh `_recover_feature_error`, `_inspect_output`, `on_output`, cleanup/`_complete_inflight` bodies for accurate anchors.
2. Finalize findings (likely: 1× P4 doc inconsistency in `fortigate/docker/README.md` new paragraph naming `FOS_EXIT_ON_BOOTSTRAP_ERROR`; possibly 1× P4 test simplification in `test_common_stack_boundaries.py`), then emit the trusted result schema with disclosure that no tests were executed and manifest `incomplete: true`.

## Relevant Files
- `/source/manifest.json`, `/source/diff.txt`: inventory and full PR diff (both read; diff line offsets listed in Important Details).
- `/source/head/fortinet/common/fos_commander.py`: core scheduler; lines 1–360 fresh (CLI_PROMPT_CONTEXT_PATTERN at 30-33, `MAX_COMMAND_RECOVERY_RETRIES` at 45); lines 360–687 summarized only — may re-read for anchors.
- `/source/head/fortinet/common/cli_commands.py` (207 lines), `common.py` (92), `env.py` (48), `terminal.py`, `fos_cli_driver.py`, `launch.py`: fully read.
- `/source/head/fortinet/common/features/{base,credentials,license,startup_config,pki}.py`: fully read; license.py and pki.py are context-only (not in changed list; pki diff is comment-only).
- `/source/head/fortinet/fortigate/README.md`, `/source/head/fortinet/fortigate/docker/README.md`: fully read; docker README lines ~137 and ~311 relevant to the doc-inconsistency finding.
- `/source/head/fortinet/tests/test_common_*.py`: all fully read; helpers (`SerialConnection`, `RecordingFeature`) in `test_common_stack_parsing.py`; `state_case` duplication in `test_common_stack_boundaries.py` (~lines 105-108).
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d93e2e001ej1j0FXkYtKUeU",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d8de4a0013MLZ4yeLcsV2WF",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 37403,
    "input": 34022,
    "output": 2848,
    "reasoning": 533,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d8de4a0013MLZ4yeLcsV2WF",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716706890,
    "completed": 1793716731442
  },
  "parentID": "msg_1a1d8de33001pET7RWke6yehD9",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 37403,
    "input": 34022,
    "output": 2848,
    "reasoning": 533,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 37
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_1a1d93e33001yKp1QAF8LFj4JT",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716731443
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 38
step-start
{
  "type": "step-start",
  "id": "prt_1a1d9435b001HtOgSBB6XsGZrT",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d93e3a001LR04KuIDHuPU2E"
}
Reasoning
Continue: re-read fos_commander.py lines 360-687 for anchors, then finalize.
read · completed

Input

{
  "filePath": "/source/head/fortinet/common/fos_commander.py",
  "offset": 360
}

Output

<path>/source/head/fortinet/common/fos_commander.py</path>
<type>file</type>
<content>
360:                 if self._feature_errors:
361:                     failed = ", ".join(name for name, _error in self._feature_errors)
362:                     self.logger.error(
363:                         "Bootstrap reached the end with %d feature error(s) in %s; "
364:                         "failed work: %s",
365:                         len(self._feature_errors),
366:                         elapsed,
367:                         failed,
368:                     )
369:                 else:
370:                     self.logger.info(f"Startup complete in {elapsed}")
371:             else:
372:                 while self._completed_messages:
373:                     self.logger.info(self._completed_messages.popleft())
374:             return
375:         self._active_feature = self._features.popleft()
376:         self.logger.info(f"Activating feature {self._active_feature.name}")
377:         self._call_feature(self._active_feature.begin_activation)
378:         if self._pending_feature_error is None:
379:             self._call_feature(self._active_feature.activate)
380: 
381:     def _dispatch_next(self):
382:         if self._inflight or self._recovering or self._pending_feature_error is not None:
383:             return
384:         if not self._restore_replay_context():
385:             return
386:         if not self._cleanup and self._active_feature is None:
387:             self._activate_next_feature()
388:             if self._active_feature is None:
389:                 return
390:         if self._cleanup:
391:             spec = self._cleanup.popleft()
392:             self._in_cleanup = True
393:             block_index = None
394:         elif not self._pending:
395:             self._call_feature(self._active_feature.on_block_complete)
396:             return
397:         else:
398:             spec = self._pending.popleft()
399:             self._in_cleanup = False
400:             block_index = len(self._active_commands) - len(self._pending) - 1
401:         self._dispatch_command(spec, block_index)
402: 
403:     def _dispatch_command(self, spec, block_index=None):
404:         self._attempt_number += 1
405:         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)
406:         self._inflight.prompt_context_before = self._prompt_context
407:         self._inflight.block_index = block_index
408:         self._inflight.retry_count = (
409:             self._cleanup_retries.get(id(spec), 0)
410:             if self._in_cleanup else self._recovery_retries.get(block_index, 0)
411:         )
412:         if self._active_feature and not self._in_context_reset:
413:             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)
414:             if self._pending_feature_error is not None:
415:                 return
416:         if spec.suppress_output:
417:             self._suppression.enter_context(self.terminal.suppress_output())
418:         self.logger.log(
419:             TRACE_LEVEL,
420:             f"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/"
421:             f"{spec.line!r}"
422:         )
423:         self.terminal.write(f"{spec.line}\r")
424: 
425:     def _complete_inflight(self, state):
426:         attempt = self._inflight
427:         self._inflight = None
428:         self._suppression.close()
429:         self._suppression = ExitStack()
430:         attempt.prompt_context_after = self._prompt_context
431:         if self._in_context_reset:
432:             self._in_context_reset = False
433:             self._dispatch_next()
434:             return
435:         if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):
436:             self._handle_context_loss(attempt)
437:             if self._pending_feature_error is not None:
438:                 self._recover_feature_error()
439:             else:
440:                 self._dispatch_next()
441:             return
442:         try:
443:             self._validate_completion(attempt, state)
444:         except RuntimeError as error:
445:             if state != FOSCliState.CMD_PROMPT:
446:                 # An interactive prompt cannot safely advance to another feature.
447:                 raise
448:             self._handle_work_error(error)
449:             if self._pending_feature_error is not None:
450:                 self._recover_feature_error()
451:             return
452:         if self._in_cleanup:
453:             self._cleanup_retries.pop(id(attempt.spec), None)
454:             self._in_cleanup = False
455:             self._dispatch_next()
456:             return
457:         if self._is_standard_output_command(attempt.spec):
458:             self._complete_standard_output_command(attempt)
459:             if self._pending_feature_error is not None:
460:                 return
461:             if not self._recovering:
462:                 self._dispatch_next()
463:             return
464:         completed_feature = self._active_feature
465:         self._call_feature(completed_feature.on_command_executed, attempt, state)
466:         if self._pending_feature_error is not None:
467:             return
468:         # The callback may have installed another block (confirmation/query path).
469:         if not self.busy and self._active_feature is completed_feature:
470:             self._call_feature(completed_feature.on_block_complete)
471:         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:
472:             self._dispatch_next()
473: 
474:     @staticmethod
475:     def _validate_completion(attempt, state):
476:         if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (
477:             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))
478:         ):
479:             raise RuntimeError(
480:                 f"FortiOS command {attempt.spec.line!r} failed "
481:                 f"(return code {failure.group(1).decode()})"
482:             )
483:         expected = attempt.spec.expected_completion_state
484:         if expected is not None and state != expected:
485:             raise RuntimeError(
486:                 "CLI command completed at unexpected prompt: "
487:                 f"expected {expected.name}, received {state.name}"
488:             )
489: 
490:     def _prompt_context_changed(self, attempt):
491:         before = attempt.prompt_context_before
492:         after = attempt.prompt_context_after
493:         return (
494:             before is not None
495:             and after is not None
496:             and before != after
497:             and not self._command_may_change_context(attempt.spec)
498:         )
499: 
500:     def _handle_context_loss(self, attempt):
501:         reason = (
502:             "CLI context changed from "
503:             f"{self._format_prompt_context(attempt.prompt_context_before)} to "
504:             f"{self._format_prompt_context(attempt.prompt_context_after)}"
505:         )
506:         if self._in_cleanup:
507:             self._handle_work_error(RuntimeError(
508:                 f"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay"
509:             ))
510:             return
511:         action = self._call_feature(self._active_feature.on_context_loss, attempt)
512:         if self._pending_feature_error is not None:
513:             return
514:         if action == ContextLossAction.RESTART_BLOCK:
515:             self._restart_active_block(attempt, reason)
516:         elif action == ContextLossAction.FAIL:
517:             self._handle_work_error(RuntimeError(
518:                 f"{reason} during {attempt.spec.line!r}; feature declined replay"
519:             ))
520:         else:
521:             self._handle_work_error(ValueError(f"Unsupported context-loss action: {action!r}"))
522: 
523:     def _restore_replay_context(self):
524:         """Unwind a surviving partial scope once before replaying its openers."""
525:         target = self._replay_context_target
526:         if target is None:
527:             return True
528:         if self._prompt_context == target:
529:             self._replay_context_target = None
530:             return True
531:         if self._context_reset_attempted:
532:             self._handle_work_error(RuntimeError(
533:                 "Unable to restore CLI context before replay: expected "
534:                 f"{self._format_prompt_context(target)}, received "
535:                 f"{self._format_prompt_context(self._prompt_context or ())}"
536:             ))
537:             if self._pending_feature_error is not None:
538:                 self._recover_feature_error()
539:             return False
540:         self._context_reset_attempted = True
541:         self._in_context_reset = True
542:         self._dispatch_command(CommandSpec("abort", suppress_output=True))
543:         return False
544: 
545:     @staticmethod
546:     def _command_may_change_context(spec):
547:         if spec.continuation:
548:             return False
549:         command = spec.line.strip().lower()
550:         return (
551:             command.startswith(("config ", "edit "))
552:             or command in {"next", "end", "abort", "exit", "quit"}
553:             or command == "set vdom-mode multi-vdom"
554:         )
555: 
556:     @staticmethod
557:     def _extract_prompt_context(output):
558:         data = bytes(output)
559:         matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))
560:         if not matches:
561:             return None
562:         return tuple(
563:             item.decode(errors="replace")
564:             for item in re.findall(rb"\(([^)]*)\)", matches[-1].group("context"))
565:         )
566: 
567:     @staticmethod
568:     def _format_prompt_context(context):
569:         return " ".join(f"({item})" for item in context) or "<top-level>"
570: 
571:     def _is_standard_output_command(self, spec):
572:         context = self._standard_output_context
573:         return context is not None and (
574:             spec.line == self._CONSOLE_INSPECT_LINE
575:             or (context.phase == "set-standard" and not self._pending)
576:         )
577: 
578:     def _complete_standard_output_command(self, attempt):
579:         context = self._standard_output_context
580:         if attempt.spec.line == self._CONSOLE_INSPECT_LINE:
581:             match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))
582:             if not match or match.group(1) == b"standard":
583:                 if not match:
584:                     self.logger.warning("Could not determine console output mode; assuming standard output")
585:                 self._start_standard_output_callback(context)
586:                 return
587:             context.phase = "set-standard"
588:             self.submit_block(context.feature, ConfigBlock("system console", [
589:                 self._CONSOLE_STANDARD_LINE,
590:             ]))
591:             return
592:         if context.phase == "set-standard":
593:             context.restore = True
594:             self._start_standard_output_callback(context)
595: 
596:     def _start_standard_output_callback(self, context):
597:         context.phase = "active"
598:         self._call_feature(context.callback)
599: 
600:     def _finish_standard_output_context(self, feature):
601:         context = self._standard_output_context
602:         if context is None or context.feature is not feature:
603:             return
604:         self._standard_output_context = None
605:         if context.restore:
606:             self._cleanup.extend(ConfigBlock("system console", [
607:                 "set output more",
608:             ]).flatten())
609: 
610:     def _handle_session_loss(self):
611:         self._session_epoch += 1
612:         self._recovering = True
613:         if not self._inflight:
614:             return
615:         attempt = self._inflight
616:         self._inflight = None
617:         self._suppression.close()
618:         self._suppression = ExitStack()
619:         if self._in_context_reset:
620:             # Login may itself restore the target scope. The pending replay
621:             # stays bounded by the original command's recovery allowance.
622:             self._in_context_reset = False
623:             return
624:         if self._in_cleanup:
625:             retries = self._cleanup_retries.get(id(attempt.spec), 0)
626:             if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
627:                 self._handle_work_error(RuntimeError(
628:                     f"Session lost repeatedly during cleanup {attempt.spec.line!r}; "
629:                     "retry limit reached"
630:                 ))
631:                 return
632:             self._cleanup_retries[id(attempt.spec)] = retries + 1
633:             self._cleanup.appendleft(attempt.spec)
634:             self._in_cleanup = False
635:             return
636:         self._schedule_feature_cleanup(self._active_feature, "interruption")
637:         action = self._call_feature(
638:             self._active_feature.on_session_loss,
639:             attempt,
640:         )
641:         if self._pending_feature_error is not None:
642:             return
643:         self.logger.info(
644:             f"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}"
645:         )
646:         action_handlers = {
647:             SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(
648:                 attempt, "session lost"
649:             ),
650:             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),
651:             SessionLossAction.CONTINUE: lambda: self._pending.clear(),
652:             SessionLossAction.FAIL: lambda: self._handle_work_error(
653:                 RuntimeError(f"Session lost during {attempt.spec.line!r}")
654:             ),
655:             SessionLossAction.VALIDATE: lambda: self._pending.clear(),
656:         }
657:         action_handlers[action]()
658: 
659:     def _restart_active_block(self, attempt, reason):
660:         retries = self._recovery_retries.get(attempt.block_index, 0)
661:         if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:
662:             self._handle_work_error(RuntimeError(
663:                 f"{reason} repeatedly during {attempt.spec.line!r}; "
664:                 f"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})"
665:             ))
666:             return
667:         self._recovery_retries[attempt.block_index] = retries + 1
668:         self._pending = deque(self._active_commands)
669:         self._replay_context_target = self._block_prompt_context
670:         self._context_reset_attempted = False
671:         self.logger.warning(
672:             "%s during %s/%r; replaying block (command recovery %d/%d)",
673:             reason, self._active_feature.name, attempt.spec.line,
674:             retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,
675:         )
676: 
677:     def enqueue_runtime_feature(self, feature):
678:         return self.enqueue_runtime_features([feature])
679: 
680:     def enqueue_runtime_features(self, features):
681:         if not self._ready or self.busy:
682:             return False
683:         self._ready = False
684:         self._completed_messages.clear()
685:         for feature in reversed(features):
686:             self._features.appendleft(feature)
687:         return True

(End of file - total 687 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d9442c001bWePCgjoLo9CG5",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d93e3a001LR04KuIDHuPU2E",
  "callID": "call_3c26a4a1f62542d490d58bc6",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/common/fos_commander.py",
      "offset": 360
    },
    "output": "<path>/source/head/fortinet/common/fos_commander.py</path>\n<type>file</type>\n<content>\n360:                 if self._feature_errors:\n361:                     failed = \", \".join(name for name, _error in self._feature_errors)\n362:                     self.logger.error(\n363:                         \"Bootstrap reached the end with %d feature error(s) in %s; \"\n364:                         \"failed work: %s\",\n365:                         len(self._feature_errors),\n366:                         elapsed,\n367:                         failed,\n368:                     )\n369:                 else:\n370:                     self.logger.info(f\"Startup complete in {elapsed}\")\n371:             else:\n372:                 while self._completed_messages:\n373:                     self.logger.info(self._completed_messages.popleft())\n374:             return\n375:         self._active_feature = self._features.popleft()\n376:         self.logger.info(f\"Activating feature {self._active_feature.name}\")\n377:         self._call_feature(self._active_feature.begin_activation)\n378:         if self._pending_feature_error is None:\n379:             self._call_feature(self._active_feature.activate)\n380: \n381:     def _dispatch_next(self):\n382:         if self._inflight or self._recovering or self._pending_feature_error is not None:\n383:             return\n384:         if not self._restore_replay_context():\n385:             return\n386:         if not self._cleanup and self._active_feature is None:\n387:             self._activate_next_feature()\n388:             if self._active_feature is None:\n389:                 return\n390:         if self._cleanup:\n391:             spec = self._cleanup.popleft()\n392:             self._in_cleanup = True\n393:             block_index = None\n394:         elif not self._pending:\n395:             self._call_feature(self._active_feature.on_block_complete)\n396:             return\n397:         else:\n398:             spec = self._pending.popleft()\n399:             self._in_cleanup = False\n400:             block_index = len(self._active_commands) - len(self._pending) - 1\n401:         self._dispatch_command(spec, block_index)\n402: \n403:     def _dispatch_command(self, spec, block_index=None):\n404:         self._attempt_number += 1\n405:         self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n406:         self._inflight.prompt_context_before = self._prompt_context\n407:         self._inflight.block_index = block_index\n408:         self._inflight.retry_count = (\n409:             self._cleanup_retries.get(id(spec), 0)\n410:             if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n411:         )\n412:         if self._active_feature and not self._in_context_reset:\n413:             self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n414:             if self._pending_feature_error is not None:\n415:                 return\n416:         if spec.suppress_output:\n417:             self._suppression.enter_context(self.terminal.suppress_output())\n418:         self.logger.log(\n419:             TRACE_LEVEL,\n420:             f\"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/\"\n421:             f\"{spec.line!r}\"\n422:         )\n423:         self.terminal.write(f\"{spec.line}\\r\")\n424: \n425:     def _complete_inflight(self, state):\n426:         attempt = self._inflight\n427:         self._inflight = None\n428:         self._suppression.close()\n429:         self._suppression = ExitStack()\n430:         attempt.prompt_context_after = self._prompt_context\n431:         if self._in_context_reset:\n432:             self._in_context_reset = False\n433:             self._dispatch_next()\n434:             return\n435:         if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n436:             self._handle_context_loss(attempt)\n437:             if self._pending_feature_error is not None:\n438:                 self._recover_feature_error()\n439:             else:\n440:                 self._dispatch_next()\n441:             return\n442:         try:\n443:             self._validate_completion(attempt, state)\n444:         except RuntimeError as error:\n445:             if state != FOSCliState.CMD_PROMPT:\n446:                 # An interactive prompt cannot safely advance to another feature.\n447:                 raise\n448:             self._handle_work_error(error)\n449:             if self._pending_feature_error is not None:\n450:                 self._recover_feature_error()\n451:             return\n452:         if self._in_cleanup:\n453:             self._cleanup_retries.pop(id(attempt.spec), None)\n454:             self._in_cleanup = False\n455:             self._dispatch_next()\n456:             return\n457:         if self._is_standard_output_command(attempt.spec):\n458:             self._complete_standard_output_command(attempt)\n459:             if self._pending_feature_error is not None:\n460:                 return\n461:             if not self._recovering:\n462:                 self._dispatch_next()\n463:             return\n464:         completed_feature = self._active_feature\n465:         self._call_feature(completed_feature.on_command_executed, attempt, state)\n466:         if self._pending_feature_error is not None:\n467:             return\n468:         # The callback may have installed another block (confirmation/query path).\n469:         if not self.busy and self._active_feature is completed_feature:\n470:             self._call_feature(completed_feature.on_block_complete)\n471:         if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n472:             self._dispatch_next()\n473: \n474:     @staticmethod\n475:     def _validate_completion(attempt, state):\n476:         if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n477:             failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n478:         ):\n479:             raise RuntimeError(\n480:                 f\"FortiOS command {attempt.spec.line!r} failed \"\n481:                 f\"(return code {failure.group(1).decode()})\"\n482:             )\n483:         expected = attempt.spec.expected_completion_state\n484:         if expected is not None and state != expected:\n485:             raise RuntimeError(\n486:                 \"CLI command completed at unexpected prompt: \"\n487:                 f\"expected {expected.name}, received {state.name}\"\n488:             )\n489: \n490:     def _prompt_context_changed(self, attempt):\n491:         before = attempt.prompt_context_before\n492:         after = attempt.prompt_context_after\n493:         return (\n494:             before is not None\n495:             and after is not None\n496:             and before != after\n497:             and not self._command_may_change_context(attempt.spec)\n498:         )\n499: \n500:     def _handle_context_loss(self, attempt):\n501:         reason = (\n502:             \"CLI context changed from \"\n503:             f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n504:             f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n505:         )\n506:         if self._in_cleanup:\n507:             self._handle_work_error(RuntimeError(\n508:                 f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n509:             ))\n510:             return\n511:         action = self._call_feature(self._active_feature.on_context_loss, attempt)\n512:         if self._pending_feature_error is not None:\n513:             return\n514:         if action == ContextLossAction.RESTART_BLOCK:\n515:             self._restart_active_block(attempt, reason)\n516:         elif action == ContextLossAction.FAIL:\n517:             self._handle_work_error(RuntimeError(\n518:                 f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n519:             ))\n520:         else:\n521:             self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n522: \n523:     def _restore_replay_context(self):\n524:         \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n525:         target = self._replay_context_target\n526:         if target is None:\n527:             return True\n528:         if self._prompt_context == target:\n529:             self._replay_context_target = None\n530:             return True\n531:         if self._context_reset_attempted:\n532:             self._handle_work_error(RuntimeError(\n533:                 \"Unable to restore CLI context before replay: expected \"\n534:                 f\"{self._format_prompt_context(target)}, received \"\n535:                 f\"{self._format_prompt_context(self._prompt_context or ())}\"\n536:             ))\n537:             if self._pending_feature_error is not None:\n538:                 self._recover_feature_error()\n539:             return False\n540:         self._context_reset_attempted = True\n541:         self._in_context_reset = True\n542:         self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n543:         return False\n544: \n545:     @staticmethod\n546:     def _command_may_change_context(spec):\n547:         if spec.continuation:\n548:             return False\n549:         command = spec.line.strip().lower()\n550:         return (\n551:             command.startswith((\"config \", \"edit \"))\n552:             or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n553:             or command == \"set vdom-mode multi-vdom\"\n554:         )\n555: \n556:     @staticmethod\n557:     def _extract_prompt_context(output):\n558:         data = bytes(output)\n559:         matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n560:         if not matches:\n561:             return None\n562:         return tuple(\n563:             item.decode(errors=\"replace\")\n564:             for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n565:         )\n566: \n567:     @staticmethod\n568:     def _format_prompt_context(context):\n569:         return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n570: \n571:     def _is_standard_output_command(self, spec):\n572:         context = self._standard_output_context\n573:         return context is not None and (\n574:             spec.line == self._CONSOLE_INSPECT_LINE\n575:             or (context.phase == \"set-standard\" and not self._pending)\n576:         )\n577: \n578:     def _complete_standard_output_command(self, attempt):\n579:         context = self._standard_output_context\n580:         if attempt.spec.line == self._CONSOLE_INSPECT_LINE:\n581:             match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))\n582:             if not match or match.group(1) == b\"standard\":\n583:                 if not match:\n584:                     self.logger.warning(\"Could not determine console output mode; assuming standard output\")\n585:                 self._start_standard_output_callback(context)\n586:                 return\n587:             context.phase = \"set-standard\"\n588:             self.submit_block(context.feature, ConfigBlock(\"system console\", [\n589:                 self._CONSOLE_STANDARD_LINE,\n590:             ]))\n591:             return\n592:         if context.phase == \"set-standard\":\n593:             context.restore = True\n594:             self._start_standard_output_callback(context)\n595: \n596:     def _start_standard_output_callback(self, context):\n597:         context.phase = \"active\"\n598:         self._call_feature(context.callback)\n599: \n600:     def _finish_standard_output_context(self, feature):\n601:         context = self._standard_output_context\n602:         if context is None or context.feature is not feature:\n603:             return\n604:         self._standard_output_context = None\n605:         if context.restore:\n606:             self._cleanup.extend(ConfigBlock(\"system console\", [\n607:                 \"set output more\",\n608:             ]).flatten())\n609: \n610:     def _handle_session_loss(self):\n611:         self._session_epoch += 1\n612:         self._recovering = True\n613:         if not self._inflight:\n614:             return\n615:         attempt = self._inflight\n616:         self._inflight = None\n617:         self._suppression.close()\n618:         self._suppression = ExitStack()\n619:         if self._in_context_reset:\n620:             # Login may itself restore the target scope. The pending replay\n621:             # stays bounded by the original command's recovery allowance.\n622:             self._in_context_reset = False\n623:             return\n624:         if self._in_cleanup:\n625:             retries = self._cleanup_retries.get(id(attempt.spec), 0)\n626:             if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n627:                 self._handle_work_error(RuntimeError(\n628:                     f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n629:                     \"retry limit reached\"\n630:                 ))\n631:                 return\n632:             self._cleanup_retries[id(attempt.spec)] = retries + 1\n633:             self._cleanup.appendleft(attempt.spec)\n634:             self._in_cleanup = False\n635:             return\n636:         self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n637:         action = self._call_feature(\n638:             self._active_feature.on_session_loss,\n639:             attempt,\n640:         )\n641:         if self._pending_feature_error is not None:\n642:             return\n643:         self.logger.info(\n644:             f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n645:         )\n646:         action_handlers = {\n647:             SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n648:                 attempt, \"session lost\"\n649:             ),\n650:             SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n651:             SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n652:             SessionLossAction.FAIL: lambda: self._handle_work_error(\n653:                 RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n654:             ),\n655:             SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n656:         }\n657:         action_handlers[action]()\n658: \n659:     def _restart_active_block(self, attempt, reason):\n660:         retries = self._recovery_retries.get(attempt.block_index, 0)\n661:         if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n662:             self._handle_work_error(RuntimeError(\n663:                 f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n664:                 f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n665:             ))\n666:             return\n667:         self._recovery_retries[attempt.block_index] = retries + 1\n668:         self._pending = deque(self._active_commands)\n669:         self._replay_context_target = self._block_prompt_context\n670:         self._context_reset_attempted = False\n671:         self.logger.warning(\n672:             \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n673:             reason, self._active_feature.name, attempt.spec.line,\n674:             retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n675:         )\n676: \n677:     def enqueue_runtime_feature(self, feature):\n678:         return self.enqueue_runtime_features([feature])\n679: \n680:     def enqueue_runtime_features(self, features):\n681:         if not self._ready or self.busy:\n682:             return False\n683:         self._ready = False\n684:         self._completed_messages.clear()\n685:         for feature in reversed(features):\n686:             self._features.appendleft(feature)\n687:         return True\n\n(End of file - total 687 lines)\n</content>",
    "title": "source/head/fortinet/common/fos_commander.py",
    "metadata": {
      "preview": "                if self._feature_errors:\n                    failed = \", \".join(name for name, _error in self._feature_errors)\n                    self.logger.error(\n                        \"Bootstrap reached the end with %d feature error(s) in %s; \"\n                        \"failed work: %s\",\n                        len(self._feature_errors),\n                        elapsed,\n                        failed,\n                    )\n                else:\n                    self.logger.info(f\"Startup complete in {elapsed}\")\n            else:\n                while self._completed_messages:\n                    self.logger.info(self._completed_messages.popleft())\n            return\n        self._active_feature = self._features.popleft()\n        self.logger.info(f\"Activating feature {self._active_feature.name}\")\n        self._call_feature(self._active_feature.begin_activation)\n        if self._pending_feature_error is None:\n            self._call_feature(self._active_feature.activate)",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/common/fos_commander.py",
        "text": "                if self._feature_errors:\n                    failed = \", \".join(name for name, _error in self._feature_errors)\n                    self.logger.error(\n                        \"Bootstrap reached the end with %d feature error(s) in %s; \"\n                        \"failed work: %s\",\n                        len(self._feature_errors),\n                        elapsed,\n                        failed,\n                    )\n                else:\n                    self.logger.info(f\"Startup complete in {elapsed}\")\n            else:\n                while self._completed_messages:\n                    self.logger.info(self._completed_messages.popleft())\n            return\n        self._active_feature = self._features.popleft()\n        self.logger.info(f\"Activating feature {self._active_feature.name}\")\n        self._call_feature(self._active_feature.begin_activation)\n        if self._pending_feature_error is None:\n            self._call_feature(self._active_feature.activate)\n\n    def _dispatch_next(self):\n        if self._inflight or self._recovering or self._pending_feature_error is not None:\n            return\n        if not self._restore_replay_context():\n            return\n        if not self._cleanup and self._active_feature is None:\n            self._activate_next_feature()\n            if self._active_feature is None:\n                return\n        if self._cleanup:\n            spec = self._cleanup.popleft()\n            self._in_cleanup = True\n            block_index = None\n        elif not self._pending:\n            self._call_feature(self._active_feature.on_block_complete)\n            return\n        else:\n            spec = self._pending.popleft()\n            self._in_cleanup = False\n            block_index = len(self._active_commands) - len(self._pending) - 1\n        self._dispatch_command(spec, block_index)\n\n    def _dispatch_command(self, spec, block_index=None):\n        self._attempt_number += 1\n        self._inflight = CommandAttempt(spec, self._attempt_number, self._session_epoch)\n        self._inflight.prompt_context_before = self._prompt_context\n        self._inflight.block_index = block_index\n        self._inflight.retry_count = (\n            self._cleanup_retries.get(id(spec), 0)\n            if self._in_cleanup else self._recovery_retries.get(block_index, 0)\n        )\n        if self._active_feature and not self._in_context_reset:\n            self._call_feature(self._active_feature.on_command_dispatched, self._inflight)\n            if self._pending_feature_error is not None:\n                return\n        if spec.suppress_output:\n            self._suppression.enter_context(self.terminal.suppress_output())\n        self.logger.log(\n            TRACE_LEVEL,\n            f\"Dispatching {(self._active_feature.name if self._active_feature else 'cleanup')}/\"\n            f\"{spec.line!r}\"\n        )\n        self.terminal.write(f\"{spec.line}\\r\")\n\n    def _complete_inflight(self, state):\n        attempt = self._inflight\n        self._inflight = None\n        self._suppression.close()\n        self._suppression = ExitStack()\n        attempt.prompt_context_after = self._prompt_context\n        if self._in_context_reset:\n            self._in_context_reset = False\n            self._dispatch_next()\n            return\n        if state == FOSCliState.CMD_PROMPT and self._prompt_context_changed(attempt):\n            self._handle_context_loss(attempt)\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            else:\n                self._dispatch_next()\n            return\n        try:\n            self._validate_completion(attempt, state)\n        except RuntimeError as error:\n            if state != FOSCliState.CMD_PROMPT:\n                # An interactive prompt cannot safely advance to another feature.\n                raise\n            self._handle_work_error(error)\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            return\n        if self._in_cleanup:\n            self._cleanup_retries.pop(id(attempt.spec), None)\n            self._in_cleanup = False\n            self._dispatch_next()\n            return\n        if self._is_standard_output_command(attempt.spec):\n            self._complete_standard_output_command(attempt)\n            if self._pending_feature_error is not None:\n                return\n            if not self._recovering:\n                self._dispatch_next()\n            return\n        completed_feature = self._active_feature\n        self._call_feature(completed_feature.on_command_executed, attempt, state)\n        if self._pending_feature_error is not None:\n            return\n        # The callback may have installed another block (confirmation/query path).\n        if not self.busy and self._active_feature is completed_feature:\n            self._call_feature(completed_feature.on_block_complete)\n        if not self._recovering and state in DISPATCHABLE_COMPLETION_STATES:\n            self._dispatch_next()\n\n    @staticmethod\n    def _validate_completion(attempt, state):\n        if (attempt.spec.closes_scope or attempt.spec.fail_on_error) and (\n            failure := COMMAND_FAILURE_PATTERN.search(bytes(attempt.output))\n        ):\n            raise RuntimeError(\n                f\"FortiOS command {attempt.spec.line!r} failed \"\n                f\"(return code {failure.group(1).decode()})\"\n            )\n        expected = attempt.spec.expected_completion_state\n        if expected is not None and state != expected:\n            raise RuntimeError(\n                \"CLI command completed at unexpected prompt: \"\n                f\"expected {expected.name}, received {state.name}\"\n            )\n\n    def _prompt_context_changed(self, attempt):\n        before = attempt.prompt_context_before\n        after = attempt.prompt_context_after\n        return (\n            before is not None\n            and after is not None\n            and before != after\n            and not self._command_may_change_context(attempt.spec)\n        )\n\n    def _handle_context_loss(self, attempt):\n        reason = (\n            \"CLI context changed from \"\n            f\"{self._format_prompt_context(attempt.prompt_context_before)} to \"\n            f\"{self._format_prompt_context(attempt.prompt_context_after)}\"\n        )\n        if self._in_cleanup:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} during cleanup {attempt.spec.line!r}; no feature block to replay\"\n            ))\n            return\n        action = self._call_feature(self._active_feature.on_context_loss, attempt)\n        if self._pending_feature_error is not None:\n            return\n        if action == ContextLossAction.RESTART_BLOCK:\n            self._restart_active_block(attempt, reason)\n        elif action == ContextLossAction.FAIL:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} during {attempt.spec.line!r}; feature declined replay\"\n            ))\n        else:\n            self._handle_work_error(ValueError(f\"Unsupported context-loss action: {action!r}\"))\n\n    def _restore_replay_context(self):\n        \"\"\"Unwind a surviving partial scope once before replaying its openers.\"\"\"\n        target = self._replay_context_target\n        if target is None:\n            return True\n        if self._prompt_context == target:\n            self._replay_context_target = None\n            return True\n        if self._context_reset_attempted:\n            self._handle_work_error(RuntimeError(\n                \"Unable to restore CLI context before replay: expected \"\n                f\"{self._format_prompt_context(target)}, received \"\n                f\"{self._format_prompt_context(self._prompt_context or ())}\"\n            ))\n            if self._pending_feature_error is not None:\n                self._recover_feature_error()\n            return False\n        self._context_reset_attempted = True\n        self._in_context_reset = True\n        self._dispatch_command(CommandSpec(\"abort\", suppress_output=True))\n        return False\n\n    @staticmethod\n    def _command_may_change_context(spec):\n        if spec.continuation:\n            return False\n        command = spec.line.strip().lower()\n        return (\n            command.startswith((\"config \", \"edit \"))\n            or command in {\"next\", \"end\", \"abort\", \"exit\", \"quit\"}\n            or command == \"set vdom-mode multi-vdom\"\n        )\n\n    @staticmethod\n    def _extract_prompt_context(output):\n        data = bytes(output)\n        matches = list(CLI_PROMPT_CONTEXT_PATTERN.finditer(data))\n        if not matches:\n            return None\n        return tuple(\n            item.decode(errors=\"replace\")\n            for item in re.findall(rb\"\\(([^)]*)\\)\", matches[-1].group(\"context\"))\n        )\n\n    @staticmethod\n    def _format_prompt_context(context):\n        return \" \".join(f\"({item})\" for item in context) or \"<top-level>\"\n\n    def _is_standard_output_command(self, spec):\n        context = self._standard_output_context\n        return context is not None and (\n            spec.line == self._CONSOLE_INSPECT_LINE\n            or (context.phase == \"set-standard\" and not self._pending)\n        )\n\n    def _complete_standard_output_command(self, attempt):\n        context = self._standard_output_context\n        if attempt.spec.line == self._CONSOLE_INSPECT_LINE:\n            match = self._CONSOLE_OUTPUT_PATTERN.search(bytes(attempt.output))\n            if not match or match.group(1) == b\"standard\":\n                if not match:\n                    self.logger.warning(\"Could not determine console output mode; assuming standard output\")\n                self._start_standard_output_callback(context)\n                return\n            context.phase = \"set-standard\"\n            self.submit_block(context.feature, ConfigBlock(\"system console\", [\n                self._CONSOLE_STANDARD_LINE,\n            ]))\n            return\n        if context.phase == \"set-standard\":\n            context.restore = True\n            self._start_standard_output_callback(context)\n\n    def _start_standard_output_callback(self, context):\n        context.phase = \"active\"\n        self._call_feature(context.callback)\n\n    def _finish_standard_output_context(self, feature):\n        context = self._standard_output_context\n        if context is None or context.feature is not feature:\n            return\n        self._standard_output_context = None\n        if context.restore:\n            self._cleanup.extend(ConfigBlock(\"system console\", [\n                \"set output more\",\n            ]).flatten())\n\n    def _handle_session_loss(self):\n        self._session_epoch += 1\n        self._recovering = True\n        if not self._inflight:\n            return\n        attempt = self._inflight\n        self._inflight = None\n        self._suppression.close()\n        self._suppression = ExitStack()\n        if self._in_context_reset:\n            # Login may itself restore the target scope. The pending replay\n            # stays bounded by the original command's recovery allowance.\n            self._in_context_reset = False\n            return\n        if self._in_cleanup:\n            retries = self._cleanup_retries.get(id(attempt.spec), 0)\n            if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n                self._handle_work_error(RuntimeError(\n                    f\"Session lost repeatedly during cleanup {attempt.spec.line!r}; \"\n                    \"retry limit reached\"\n                ))\n                return\n            self._cleanup_retries[id(attempt.spec)] = retries + 1\n            self._cleanup.appendleft(attempt.spec)\n            self._in_cleanup = False\n            return\n        self._schedule_feature_cleanup(self._active_feature, \"interruption\")\n        action = self._call_feature(\n            self._active_feature.on_session_loss,\n            attempt,\n        )\n        if self._pending_feature_error is not None:\n            return\n        self.logger.info(\n            f\"Session lost during {self._active_feature.name}/{attempt.spec.line!r}; {action.name.lower()}\"\n        )\n        action_handlers = {\n            SessionLossAction.RESTART_BLOCK: lambda: self._restart_active_block(\n                attempt, \"session lost\"\n            ),\n            SessionLossAction.COMPLETE_BLOCK: lambda: self._pending.clear(),\n            SessionLossAction.CONTINUE: lambda: self._pending.clear(),\n            SessionLossAction.FAIL: lambda: self._handle_work_error(\n                RuntimeError(f\"Session lost during {attempt.spec.line!r}\")\n            ),\n            SessionLossAction.VALIDATE: lambda: self._pending.clear(),\n        }\n        action_handlers[action]()\n\n    def _restart_active_block(self, attempt, reason):\n        retries = self._recovery_retries.get(attempt.block_index, 0)\n        if retries >= self.MAX_COMMAND_RECOVERY_RETRIES:\n            self._handle_work_error(RuntimeError(\n                f\"{reason} repeatedly during {attempt.spec.line!r}; \"\n                f\"retry limit reached ({self.MAX_COMMAND_RECOVERY_RETRIES})\"\n            ))\n            return\n        self._recovery_retries[attempt.block_index] = retries + 1\n        self._pending = deque(self._active_commands)\n        self._replay_context_target = self._block_prompt_context\n        self._context_reset_attempted = False\n        self.logger.warning(\n            \"%s during %s/%r; replaying block (command recovery %d/%d)\",\n            reason, self._active_feature.name, attempt.spec.line,\n            retries + 1, self.MAX_COMMAND_RECOVERY_RETRIES,\n        )\n\n    def enqueue_runtime_feature(self, feature):\n        return self.enqueue_runtime_features([feature])\n\n    def enqueue_runtime_features(self, features):\n        if not self._ready or self.busy:\n            return False\n        self._ready = False\n        self._completed_messages.clear()\n        for feature in reversed(features):\n            self._features.appendleft(feature)\n        return True",
        "lineStart": 360,
        "lineEnd": 687,
        "totalLines": 687,
        "truncated": false
      }
    },
    "time": {
      "start": 1793716732975,
      "end": 1793716732982
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/fortinet/tests/test_common_stack_boundaries.py",
  "offset": 90,
  "limit": 40
}

Output

<path>/source/head/fortinet/tests/test_common_stack_boundaries.py</path>
<type>file</type>
<content>
90:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.05), \
91:                 patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
92:             driver.process_state()
93:         assert commander.ready
94:         assert feature.completed
95:         assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT
96:         assert b"captured diagnostic" in feature.outputs[0][0]
97:         assert FOSCliState.CMD_PROMPT_ECHO in states
98:     finally:
99:         if not connection.closed:
100:             terminal.close()
101: 
102: 
103: def state_case(state, sample, suffix=b"", *, recover=False):
104:     response = sample + suffix
105:     if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):
106:         completion = (FOSCliState.CMD_PROMPT,)
107:     elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):
108:         completion = (FOSCliState.CMD_PROMPT,)
109:     else:
110:         completion = (state,)
111:     connection, terminal, commander, driver, feature, states = make_stack(
112:         CommandSpec("probe", completion_states=completion, capture_output=True),
113:         response,
114:         allow_recovery=recover,
115:         initial_prompt=b"fw (global) #" if state == FOSCliState.CMD_PROMPT_ECHO else b"fw #",
116:     )
117:     try:
118:         with patch("fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS", 0.03), \
119:                 patch("fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS", 1):
120:             driver.process_state()
121:         assert state in states
122:         assert commander.ready
123:         assert feature.completed
124:     finally:
125:         if not connection.closed:
126:             terminal.close()
127: 
128: 
129: class EndToEndBoundaryCases(unittest.TestCase):

(Showing lines 90-129 of 349. Use offset=130 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d944a6001n2Hs52bjX1zArm",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d93e3a001LR04KuIDHuPU2E",
  "callID": "call_8eb79304eb054f32a606dafb",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/tests/test_common_stack_boundaries.py",
      "offset": 90,
      "limit": 40
    },
    "output": "<path>/source/head/fortinet/tests/test_common_stack_boundaries.py</path>\n<type>file</type>\n<content>\n90:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n91:                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n92:             driver.process_state()\n93:         assert commander.ready\n94:         assert feature.completed\n95:         assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT\n96:         assert b\"captured diagnostic\" in feature.outputs[0][0]\n97:         assert FOSCliState.CMD_PROMPT_ECHO in states\n98:     finally:\n99:         if not connection.closed:\n100:             terminal.close()\n101: \n102: \n103: def state_case(state, sample, suffix=b\"\", *, recover=False):\n104:     response = sample + suffix\n105:     if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):\n106:         completion = (FOSCliState.CMD_PROMPT,)\n107:     elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):\n108:         completion = (FOSCliState.CMD_PROMPT,)\n109:     else:\n110:         completion = (state,)\n111:     connection, terminal, commander, driver, feature, states = make_stack(\n112:         CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n113:         response,\n114:         allow_recovery=recover,\n115:         initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n116:     )\n117:     try:\n118:         with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n119:                 patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n120:             driver.process_state()\n121:         assert state in states\n122:         assert commander.ready\n123:         assert feature.completed\n124:     finally:\n125:         if not connection.closed:\n126:             terminal.close()\n127: \n128: \n129: class EndToEndBoundaryCases(unittest.TestCase):\n\n(Showing lines 90-129 of 349. Use offset=130 to continue.)\n</content>",
    "title": "source/head/fortinet/tests/test_common_stack_boundaries.py",
    "metadata": {
      "preview": "        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n            driver.process_state()\n        assert commander.ready\n        assert feature.completed\n        assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT\n        assert b\"captured diagnostic\" in feature.outputs[0][0]\n        assert FOSCliState.CMD_PROMPT_ECHO in states\n    finally:\n        if not connection.closed:\n            terminal.close()\n\n\ndef state_case(state, sample, suffix=b\"\", *, recover=False):\n    response = sample + suffix\n    if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):\n        completion = (FOSCliState.CMD_PROMPT,)\n    elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):\n        completion = (FOSCliState.CMD_PROMPT,)\n    else:",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/tests/test_common_stack_boundaries.py",
        "text": "        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.05), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n            driver.process_state()\n        assert commander.ready\n        assert feature.completed\n        assert feature.outputs[0][1] == FOSCliState.CMD_PROMPT\n        assert b\"captured diagnostic\" in feature.outputs[0][0]\n        assert FOSCliState.CMD_PROMPT_ECHO in states\n    finally:\n        if not connection.closed:\n            terminal.close()\n\n\ndef state_case(state, sample, suffix=b\"\", *, recover=False):\n    response = sample + suffix\n    if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME):\n        completion = (FOSCliState.CMD_PROMPT,)\n    elif state in (FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):\n        completion = (FOSCliState.CMD_PROMPT,)\n    else:\n        completion = (state,)\n    connection, terminal, commander, driver, feature, states = make_stack(\n        CommandSpec(\"probe\", completion_states=completion, capture_output=True),\n        response,\n        allow_recovery=recover,\n        initial_prompt=b\"fw (global) #\" if state == FOSCliState.CMD_PROMPT_ECHO else b\"fw #\",\n    )\n    try:\n        with patch(\"fortinet.common.fos_cli_driver.EXPECT_TIMEOUT_SECONDS\", 0.03), \\\n                patch(\"fortinet.common.fos_cli_driver.PROCESS_SPIN_SECONDS\", 1):\n            driver.process_state()\n        assert state in states\n        assert commander.ready\n        assert feature.completed\n    finally:\n        if not connection.closed:\n            terminal.close()\n\n\nclass EndToEndBoundaryCases(unittest.TestCase):",
        "lineStart": 90,
        "lineEnd": 129,
        "totalLines": 349,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716733099,
      "end": 1793716733105
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d944b3001z9Jdqq0vgL7R1j",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d93e3a001LR04KuIDHuPU2E",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 6456,
    "input": 5161,
    "output": 58,
    "reasoning": 21,
    "cache": {
      "read": 1216,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d93e3a001LR04KuIDHuPU2E",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716731450,
    "completed": 1793716733112
  },
  "parentID": "msg_1a1d93e33001yKp1QAF8LFj4JT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 6456,
    "input": 5161,
    "output": 58,
    "reasoning": 21,
    "cache": {
      "read": 1216,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 39
step-start
{
  "type": "step-start",
  "id": "prt_1a1d94b0e001GOmGQYg3wq3gyR",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d944c2001wfx1IY6X1p986T"
}
Reasoning
Both P4 candidates confirmed with exact anchors:

1. `test_common_stack_boundaries.py:105-108` — both branches assign `completion = (FOSCliState.CMD_PROMPT,)`. The two if/elif branches are identical. This is a trivial simplification (P4, optional). Actually is it confusing? The two branches group different states but produce same completion. Minor maintainability. P4.

2. docker README `FOS_EXIT_ON_BOOTSTRAP_ERROR` vs `FTNT_EXIT_ON_BOOTSTRAP_ERROR`. Let me verify the exact lines in the docker README. From the summary: line ~137 new paragraph says `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, line ~311 says `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`. Let me grep for exact line numbers to be precise.

Also should check the diff to confirm the new paragraph introduced by PR contains FOS_. Let me grep head docker README for both spellings.
Both P4 candidates are confirmed at exact anchors. Let me pin down the README line numbers precisely.
grep · completed

Input

{
  "pattern": "EXIT_ON_BOOTSTRAP_ERROR",
  "path": "/source/head/fortinet/fortigate"
}

Output

Found 4 matches
/source/head/fortinet/fortigate/README.md:
  Line 97: | `FTNT_EXIT_ON_BOOTSTRAP_ERROR` | `true` | `true`, `false` | Stops the launcher with a nonzero exit status when a bootstrap feature raises an error. With `false`, a failed feature is skipped and later features continue when FortiOS is back at a command prompt. After a rejected desired-password login, the launcher always retries the last accepted credentials once for that login while retaining the desired credentials for subsequent logins. It does not replay an admin password change after FortiOS has committed it. Unrecoverable console or login errors leave the VM running, release the launcher's serial Telnet connection, and halt bootstrap for manual repair. Unresolved recovery or skipped features keep the VM unhealthy; a later successful login with the desired credentials clears a transient credential-recovery error. |

  Line 471:   `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, failures at a command prompt are logged


/source/head/fortinet/fortigate/docker/README.md:
  Line 139: `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for

  Line 311: `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, a failed feature is logged and skipped
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d951a30011nVWwZKQKB30s2",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d944c2001wfx1IY6X1p986T",
  "callID": "call_83fc40861d914eac88400d62",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "EXIT_ON_BOOTSTRAP_ERROR",
      "path": "/source/head/fortinet/fortigate"
    },
    "output": "Found 4 matches\n/source/head/fortinet/fortigate/README.md:\n  Line 97: | `FTNT_EXIT_ON_BOOTSTRAP_ERROR` | `true` | `true`, `false` | Stops the launcher with a nonzero exit status when a bootstrap feature raises an error. With `false`, a failed feature is skipped and later features continue when FortiOS is back at a command prompt. After a rejected desired-password login, the launcher always retries the last accepted credentials once for that login while retaining the desired credentials for subsequent logins. It does not replay an admin password change after FortiOS has committed it. Unrecoverable console or login errors leave the VM running, release the launcher's serial Telnet connection, and halt bootstrap for manual repair. Unresolved recovery or skipped features keep the VM unhealthy; a later successful login with the desired credentials clears a transient credential-recovery error. |\n\n  Line 471:   `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, failures at a command prompt are logged\n\n\n/source/head/fortinet/fortigate/docker/README.md:\n  Line 139: `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n\n  Line 311: `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false`, a failed feature is logged and skipped\n",
    "title": "EXIT_ON_BOOTSTRAP_ERROR",
    "metadata": {
      "matches": 4,
      "truncated": false
    },
    "time": {
      "start": 1793716736423,
      "end": 1793716736431
    }
  }
}
grep · completed

Input

{
  "pattern": "FOS_|FTNT_",
  "path": "/source/diff.txt",
  "include": "*.txt"
}

Output

Found 17 matches
/source/diff.txt:
  Line 202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (

  Line 204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb"(?mi)Do you want to continue\?"

  Line 205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb"(?mi)^Confirm Password:[ \t]*"

  Line 206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb"--More--\s*"

  Line 207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb"(?m)^>[ \t]*\r?$"

  Line 208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (

  Line 328:              "FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL"

  Line 1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config

  Line 1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS

  Line 1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup

  Line 1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for

  Line 1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint

  Line 2031:          with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}):

  Line 2033: -        with patch.dict("os.environ", {"FOS_TERMINAL_BUFFER_LIMIT_BYTES": "0"}):

  Line 2034: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "64", "FOS_TERMINAL_BUFFER_LIMIT_BYTES": "32"}, clear=True):

  Line 2036: +        with patch.dict("os.environ", {"FTNT_TERMINAL_BUFFER_LIMIT_BYTES": "0"}, clear=True):

  Line 2041: +        for env_name in ("FTNT_LOG_RAW_SERIAL", "FOS_LOG_RAW_SERIAL"):
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d95258001gNR2NLGCIA5r0o",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d944c2001wfx1IY6X1p986T",
  "callID": "call_cefd08d676ac499482aba360",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "FOS_|FTNT_",
      "path": "/source/diff.txt",
      "include": "*.txt"
    },
    "output": "Found 17 matches\n/source/diff.txt:\n  Line 202: @@ -60,10 +61,14 @@ FOS_CLI_STATE_PATTERNS[FOSCliState.CURRENT_PASSWORD.value] = (\n\n  Line 204:  FOS_CLI_STATE_PATTERNS[FOSCliState.CONFIRMATION.value] = rb\"(?mi)Do you want to continue\\?\"\n\n  Line 205:  FOS_CLI_STATE_PATTERNS[FOSCliState.CHANGE_PASSWORD_CONFIRM.value] = rb\"(?mi)^Confirm Password:[ \\t]*\"\n\n  Line 206:  FOS_CLI_STATE_PATTERNS[FOSCliState.MORE_PROMPT.value] = rb\"--More--\\s*\"\n\n  Line 207:  FOS_CLI_STATE_PATTERNS[FOSCliState.MULTILINE_PROMPT.value] = rb\"(?m)^>[ \\t]*\\r?$\"\n\n  Line 208: +FOS_CLI_STATE_PATTERNS[FOSCliState.KERNEL_PANIC.value] = (\n\n  Line 328:              \"FTNT_DNS_SECONDARY, or FTNT_DNS_PROTOCOL\"\n\n  Line 1001:  `FTNT_DNS_PRIMARY` / `FTNT_DNS_SECONDARY` persist through startup config\n\n  Line 1002:  application. When `FTNT_FORTIGUARD_HOOKS` is set together with either DNS\n\n  Line 1003:  variable or `FTNT_DNS_PROTOCOL`, a `config system dns` block in the startup\n\n  Line 1037: +`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n\n  Line 1098:    the product wrapper and optional `FTNT_PRODUCT_VERSION` constraint\n\n  Line 2031:          with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}):\n\n  Line 2033: -        with patch.dict(\"os.environ\", {\"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}):\n\n  Line 2034: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"64\", \"FOS_TERMINAL_BUFFER_LIMIT_BYTES\": \"32\"}, clear=True):\n\n  Line 2036: +        with patch.dict(\"os.environ\", {\"FTNT_TERMINAL_BUFFER_LIMIT_BYTES\": \"0\"}, clear=True):\n\n  Line 2041: +        for env_name in (\"FTNT_LOG_RAW_SERIAL\", \"FOS_LOG_RAW_SERIAL\"):\n",
    "title": "FOS_|FTNT_",
    "metadata": {
      "matches": 17,
      "truncated": false
    },
    "time": {
      "start": 1793716736604,
      "end": 1793716736618
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d9526c0015elkEr6RT6Wg1H",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d944c2001wfx1IY6X1p986T",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 11053,
    "input": 4377,
    "output": 78,
    "reasoning": 198,
    "cache": {
      "read": 6400,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d944c2001wfx1IY6X1p986T",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716733123,
    "completed": 1793716736623
  },
  "parentID": "msg_1a1d93e33001yKp1QAF8LFj4JT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 11053,
    "input": 4377,
    "output": 78,
    "reasoning": 198,
    "cache": {
      "read": 6400,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 40
step-start
{
  "type": "step-start",
  "id": "prt_1a1d9579c001rDUs7LPpFnAFdo",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d95278001AeNTLfPD98tIgy"
}
Reasoning
Confirmed: docker/README.md line 139 (introduced by this PR, diff line 1037) says `FOS_EXIT_ON_BOOTSTRAP_ERROR=false` while the same file's line 311 (and top-level README line 97/471) use `FTNT_EXIT_ON_BOOTSTRAP_ERROR`. Both are functionally accepted via env.py aliasing, so it's a doc consistency issue (P4).

Let me get the exact context of the docker README line 139 paragraph for the finding. Read lines ~130-145.

Also confirm test_common_stack_boundaries.py state_case: lines 105-108, both branches identical assignment. Mergeable. P4 optional.

Let me read docker README around 130-145 to cite the paragraph.
read · completed

Input

{
  "filePath": "/source/head/fortinet/fortigate/docker/README.md",
  "offset": 130,
  "limit": 18
}

Output

<path>/source/head/fortinet/fortigate/docker/README.md</path>
<type>file</type>
<content>
130: before continuing. By default, a command completes at the next command prompt.
131: Some commands override completion states, for example confirmation prompts or
132: reboot messages.
133: 
134: Scope-closing commands (`next` and `end`) always capture their output and check
135: for `Command fail. Return code <number>`, including builds that append a period
136: after the code. A closing failure stops the feature before completion callbacks
137: or further commands, even when `fail_on_error=False`. It follows the bootstrap
138: error policy: abort normally, or skip the failed feature when
139: `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for
140: individual `set` commands, which can deliberately tolerate unsupported fields.
141: 
142: Session loss is explicit. Each command carries a `SessionLossAction`:
143: 
144: - `RESTART_BLOCK`: replay the current block from the start
145: - `COMPLETE_BLOCK`: treat the block as complete
146: - `CONTINUE`: do not replay the disruptive command
147: - `VALIDATE`: reserve for commands that need post-loss validation

(Showing lines 130-147 of 500. Use offset=148 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1a1d95c7e00175HiZXGUjM8m34",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d95278001AeNTLfPD98tIgy",
  "callID": "call_9d5815e2f4b14f378219ca98",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/fortinet/fortigate/docker/README.md",
      "offset": 130,
      "limit": 18
    },
    "output": "<path>/source/head/fortinet/fortigate/docker/README.md</path>\n<type>file</type>\n<content>\n130: before continuing. By default, a command completes at the next command prompt.\n131: Some commands override completion states, for example confirmation prompts or\n132: reboot messages.\n133: \n134: Scope-closing commands (`next` and `end`) always capture their output and check\n135: for `Command fail. Return code <number>`, including builds that append a period\n136: after the code. A closing failure stops the feature before completion callbacks\n137: or further commands, even when `fail_on_error=False`. It follows the bootstrap\n138: error policy: abort normally, or skip the failed feature when\n139: `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\n140: individual `set` commands, which can deliberately tolerate unsupported fields.\n141: \n142: Session loss is explicit. Each command carries a `SessionLossAction`:\n143: \n144: - `RESTART_BLOCK`: replay the current block from the start\n145: - `COMPLETE_BLOCK`: treat the block as complete\n146: - `CONTINUE`: do not replay the disruptive command\n147: - `VALIDATE`: reserve for commands that need post-loss validation\n\n(Showing lines 130-147 of 500. Use offset=148 to continue.)\n</content>",
    "title": "source/head/fortinet/fortigate/docker/README.md",
    "metadata": {
      "preview": "before continuing. By default, a command completes at the next command prompt.\nSome commands override completion states, for example confirmation prompts or\nreboot messages.\n\nScope-closing commands (`next` and `end`) always capture their output and check\nfor `Command fail. Return code <number>`, including builds that append a period\nafter the code. A closing failure stops the feature before completion callbacks\nor further commands, even when `fail_on_error=False`. It follows the bootstrap\nerror policy: abort normally, or skip the failed feature when\n`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\nindividual `set` commands, which can deliberately tolerate unsupported fields.\n\nSession loss is explicit. Each command carries a `SessionLossAction`:\n\n- `RESTART_BLOCK`: replay the current block from the start\n- `COMPLETE_BLOCK`: treat the block as complete\n- `CONTINUE`: do not replay the disruptive command\n- `VALIDATE`: reserve for commands that need post-loss validation",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/fortinet/fortigate/docker/README.md",
        "text": "before continuing. By default, a command completes at the next command prompt.\nSome commands override completion states, for example confirmation prompts or\nreboot messages.\n\nScope-closing commands (`next` and `end`) always capture their output and check\nfor `Command fail. Return code <number>`, including builds that append a period\nafter the code. A closing failure stops the feature before completion callbacks\nor further commands, even when `fail_on_error=False`. It follows the bootstrap\nerror policy: abort normally, or skip the failed feature when\n`FOS_EXIT_ON_BOOTSTRAP_ERROR=false`. This does not change error handling for\nindividual `set` commands, which can deliberately tolerate unsupported fields.\n\nSession loss is explicit. Each command carries a `SessionLossAction`:\n\n- `RESTART_BLOCK`: replay the current block from the start\n- `COMPLETE_BLOCK`: treat the block as complete\n- `CONTINUE`: do not replay the disruptive command\n- `VALIDATE`: reserve for commands that need post-loss validation",
        "lineStart": 130,
        "lineEnd": 147,
        "totalLines": 500,
        "truncated": true
      }
    },
    "time": {
      "start": 1793716739200,
      "end": 1793716739204
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d95c86001eVgUVis0dFdXLh",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d95278001AeNTLfPD98tIgy",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 12036,
    "input": 837,
    "output": 33,
    "reasoning": 158,
    "cache": {
      "read": 11008,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d95278001AeNTLfPD98tIgy",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716736632,
    "completed": 1793716739208
  },
  "parentID": "msg_1a1d93e33001yKp1QAF8LFj4JT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 12036,
    "input": 837,
    "output": 33,
    "reasoning": 158,
    "cache": {
      "read": 11008,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 41
step-start
{
  "type": "step-start",
  "id": "prt_1a1d96193001dYiSPMEP4LPaIx",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d95c8f001cuEQ8y3TeHGgHb"
}
Reasoning
Both findings confirmed with exact anchors. Finalize the review now.

Findings:
1. P4 — `fortigate/docker/README.md:139` uses `FOS_EXIT_ON_BOOTSTRAP_ERROR` in the new "Scope-closing commands" paragraph while the same document (line 311) and the top-level `fortigate/README.md` (lines 97, 471) document `FTNT_EXIT_ON_BOOTSTRAP_ERROR` as the primary spelling. Both resolve via `env.py` aliasing, but the new paragraph introduces a second documented spelling for the same variable. Correction: use `FTNT_EXIT_ON_BOOTSTRAP_ERROR` at line 139 (or note aliasing once).

2. P4 — `test_common_stack_boundaries.py:105-108` — `state_case` assigns `completion = (FOSCliState.CMD_PROMPT,)` identically in both the `CREDENTIAL_REJECTED/PROVIDE_USERNAME` branch and the `CREDENTIAL_ACCEPTED/SESSION_LOST/CMD_PROMPT_ECHO` branch; the two branches can be merged into one `if state in (...) :` covering all five states, or simply collapsed. Optional maintainability.

Nothing else rose to a finding. Coverage: complete for source inspection; notes: no tests executed; manifest snapshot incomplete:true; standards.json empty; license.py and env.py read as context only (not in changed list); pre-existing gaps (README env-table `FTNT_FORTIGUARD_HOOKS` omission, `filter_startup_config_blocks`) not reported since not PR-introduced.

Now produce the Markdown review + final JSON. Permalinks: the publisher constructs links; but instructions say use supplied GitHub permalink roots with encoded paths and #L anchors. No roots were actually supplied in this session — I have none. I'll reference files/lines as `path:line` inline code without fabricating URLs, since no permalink roots were provided. Actually the instructions say "Use the supplied immutable GitHub link roots" — none supplied, so I'll use plain file references and note that in coverage notes? Better: just use file:line inline code; the publisher constructs source links. I'll mention in coverage notes that no permalink roots were supplied.
All investigation is complete. Here is the final review.

---

# PR Review: FortiOS CLI stack rework (context tracking, scope-commit validation, session-loss actions, recovery)

## Summary

This PR substantially reworks the FortiOS bootstrap CLI stack: prompt-context tracking (`CLI_PROMPT_CONTEXT_PATTERN`), scope-close failure detection for `closes_scope` commands, `ContextLossAction`/`SessionLossAction` recovery with block replay and bounded retries, an abort-based context restore path, retained-buffer exposure on `Data` timeouts, `FTNT_`/`FOS_` environment-variable aliasing with `TRACE_LEVEL`, and kernel-panic detection. Six new test files cover the new behaviors well.

I traced all18 changed files in full, plus context-only files (`features/license.py`, `env.py`) and every previously suspected defect path (duplicate timeout-Data consumption, `None` replay targets, `id(spec)`-keyed retry maps, context-loss ordering, credentials relogin flow, PKI TFTP fallback, startup-config quote parser). All suspected P1/P2 concerns resolved as correct-by-design. Two optional P4 findings remain.

## Findings

| Priority | Count | Titles |
| --- | --- | --- |
| P0 | 0 | — |
| P1 | 0 | — |
| P2 | 0 | — |
| P3 | 0 | — |
| P4 | 2 | New README paragraph documents `FOS_EXIT_ON_BOOTSTRAP_ERROR` instead of the primary `FTNT_` spelling; duplicated `completion` assignment in `state_case` |

### P4: New "Scope-closing commands" paragraph documents `FOS_EXIT_ON_BOOTSTRAP_ERROR` instead of the primary `FTNT_` spelling

- **Location:** `fortinet/fortigate/docker/README.md:139` (introduced by this PR, diff.txt line 1037)
- **Problem:** The new paragraph added by this PR instructs users to set `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, while the rest of the same document (`docker/README.md:311`) and the top-level `fortigate/README.md` (lines 97, 471) document `FTNT_EXIT_ON_BOOTSTRAP_ERROR` as the canonical spelling. Both spellings work because `env.py` `_candidate_names` resolves aliases, but the PR introduces a second, inconsistent documented spelling for the same variable.
- **Trigger:** A user follows the new paragraph, sets `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, then searches the docs for that name and finds only the `FTNT_` spelling elsewhere.
- **Impact:** Documentation inconsistency only; behavior is unchanged because aliasing accepts both names.
- **Correction:** Change line 139 to `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` (or add a one-line note that the `FOS_` prefix is an accepted alias), keeping the documented public interface consistent with the rest of both READMEs.

### P4: Duplicated `completion = (FOSCliState.CMD_PROMPT,)` assignment in `state_case`

- **Location:** `fortinet/tests/test_common_stack_boundaries.py:105-108`
- **Problem:** In the `state_case` helper introduced by this PR, the `if` branch (`CREDENTIAL_REJECTED`, `PROVIDE_USERNAME`) and the `elif` branch (`CREDENTIAL_ACCEPTED`, `SESSION_LOST`, `CMD_PROMPT_ECHO`) assign the identical value `completion = (FOSCliState.CMD_PROMPT,)`.
- **Trigger:** Any future reader or maintainer editing the completion mapping for these states.
- **Impact:** Cosmetic maintainability only; behavior is correct. The duplication invites an edit to one branch but not the other.
- **Correction:** Merge the two branches into a single `if state in (FOSCliState.CREDENTIAL_REJECTED, FOSCliState.PROVIDE_USERNAME, FOSCliState.CREDENTIAL_ACCEPTED, FOSCliState.SESSION_LOST, FOSCliState.CMD_PROMPT_ECHO):` condition with one assignment.

## Coverage notes

- Source-only review; no tests were executed and no formatter was run. The snapshot manifest reports `incomplete: true`, so coverage is reported as incomplete at the repository level despite full reading of all 18 changed head files, the full diff, the six test files, context-only `features/license.py` and `env.py`, and both READMEs.
- `standards.json` is empty; no repository rules were applied.
- No GitHub permalink roots were supplied in this session; file references use `path:line` inline code and the publisher can attach links.
- Pre-existing issues deliberately not reported as PR findings: the `FTNT_FORTIGUARD_HOOKS` omission from the top-level README env table and the old `filter_startup_config_blocks` code in `features/startup_config.py` (the diff only adds `_startup_config_commands`).
- The `stable_match = re.search(regex, consumed)` re-run in `terminal.py` and the `id(spec)`-keyed `_cleanup_retries` map were each investigated and judged acceptable (defensive re-run on a bounded 1 MiB buffer; retry map lifetime is bounded by cleanup completion), so neither is reported as a finding.

```json
{
  "version": 1,
  "findings": [
    {
      "priority": "P4",
      "title": "New README paragraph documents `FOS_EXIT_ON_BOOTSTRAP_ERROR` instead of the primary `FTNT_` spelling",
      "location": {
        "revision": "head",
        "path": "fortinet/fortigate/docker/README.md",
        "start": 134,
        "end": 139
      },
      "problem": "The paragraph added by this PR instructs users to set `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, while the rest of the same document (`docker/README.md` line 311) and the top-level `fortigate/README.md` (lines 97 and 471) document `FTNT_EXIT_ON_BOOTSTRAP_ERROR` as the canonical spelling. Both spellings work because `env.py` `_candidate_names` resolves aliases, but the new paragraph introduces a second, inconsistent documented spelling for the same variable.",
      "trigger": "A user follows the new paragraph, sets `FOS_EXIT_ON_BOOTSTRAP_ERROR=false`, then searches the documentation for that name and finds only the `FTNT_` spelling elsewhere.",
      "impact": "Documentation inconsistency only; runtime behavior is unchanged because the aliasing accepts both names.",
      "suggestion": "Change line 139 to `FTNT_EXIT_ON_BOOTSTRAP_ERROR=false` (or add a one-line note that the `FOS_` prefix is an accepted alias), keeping the documented public interface consistent with the rest of both READMEs."
    },
    {
      "priority": "P4",
      "title": "Duplicated `completion = (FOSCliState.CMD_PROMPT,)` assignment in `state_case`",
      "location": {
        "revision": "head",
        "path": "fortinet/tests/test_common_stack_boundaries.py",
        "start": 105,
        "end": 108
      },
      "problem": "In the `state_case` helper introduced by this PR, the `if` branch (`FOSCliState.CREDENTIAL_REJECTED`, `FOSCliState.PROVIDE_USERNAME`) and the `elif` branch (`FOSCliState.CREDENTIAL_ACCEPTED`, `FOSCliState.SESSION_LOST`, `FOSCliState.CMD_PROMPT_ECHO`) assign the identical value `completion = (FOSCliState.CMD_PROMPT,)`.",
      "trigger": "Any future maintainer editing the completion mapping for these states.",
      "impact": "Cosmetic maintainability only; behavior is correct. The duplication invites an edit to one branch but not the other.",
      "suggestion": "Merge the two branches into a single condition covering all five states with one assignment of `completion = (FOSCliState.CMD_PROMPT,)`."
    }
  ],
  "coverage": {
    "complete": false,
    "notes": [
      "Source-only review; no tests were executed and no formatter was run. The snapshot manifest reports incomplete: true, so repository-level coverage is incomplete despite full reading of all 18 changed head files, the full diff, all six test files, context-only features/license.py and env.py, and both READMEs.",
      "standards.json is empty; no repository rules were applied.",
      "No GitHub permalink roots were supplied in this session; file references use path:line inline code and the publisher can attach links.",
      "Pre-existing issues deliberately not reported as PR findings: the FTNT_FORTIGUARD_HOOKS omission from the top-level README env table and the pre-existing filter_startup_config_blocks code in features/startup_config.py, since the diff only adds _startup_config_commands.",
      "The stable_match re-run in terminal.py and the id(spec)-keyed _cleanup_retries map were investigated and judged acceptable (defensive re-run on a bounded 1 MiB buffer; retry-map lifetime bounded by cleanup completion), so neither is reported as a finding."
    ]
  }
}
```
step-finish
{
  "type": "step-finish",
  "id": "prt_1a1d99058001Mlyw7DHi4eHjgN",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "messageID": "msg_1a1d95c8f001cuEQ8y3TeHGgHb",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 14743,
    "input": 9391,
    "output": 1948,
    "reasoning": 460,
    "cache": {
      "read": 2944,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1a1d95c8f001cuEQ8y3TeHGgHb",
  "sessionID": "ses_e5e2f010fffe0ZZ3dSjJomH5F7",
  "time": {
    "created": 1793716739215,
    "completed": 1793716752475
  },
  "parentID": "msg_1a1d93e33001yKp1QAF8LFj4JT",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-cEhPOC",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 14743,
    "input": 9391,
    "output": 1948,
    "reasoning": 460,
    "cache": {
      "read": 2944,
      "write": 0
    }
  },
  "finish": "stop"
}