Skip to content

Commit b840345

Browse files
committed
feat: edit offline health check commands for SQLite databases
- Added `octop doctor db` and `octop doctor db --fix` commands for offline integrity checks and repairs of SQLite databases in `OCTOP_HOME`. - Updated relevant documentation and command references to reflect the new command structure. - Modified existing tests to align with the new command names and functionalities.
1 parent 01f7f95 commit b840345

9 files changed

Lines changed: 70 additions & 55 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
## [Unreleased]
1414

1515
### 新增
16-
- 新增 `octop db doctor` 与 `octop db recover` 离线诊断修复命令,可扫描 `OCTOP_HOME` 下所有 SQLite 库执行完整性检查,并在备份后通过 `sqlite3 .recover` / Python 回退或重置修复损坏库(#2998)。
16+
- 新增 `octop doctor db` 与 `octop doctor db --fix` 离线诊断修复命令,可扫描 `OCTOP_HOME` 下所有 SQLite 库执行完整性检查,并在备份后通过 `sqlite3 .recover` / Python 回退或重置修复损坏库(#2998)。
1717
- 可观测设置新增腾讯云 CLS(AgentObs)接入:支持填写腾讯云 SecretId / SecretKey 通过 Langfuse SDK(OTLP/HTTP Basic Auth)直接上报 Trace,支持自动调用 `CreateAgentApplication` 创建/复用 CLS 应用获取 Topic ID,也支持拉取或直接填写已有应用的 Topic ID,并提供内网接入点、内容脱敏及连通性校验。
1818
- 知识库设置新增「分块与检索」标签页,可配置分块大小、分块重叠、默认检索条数和上下文字符预算。
1919
- 用户管理支持创建限次邀请链接。链接在注册满员后自动停用,管理员也可以提前停用并查看已注册的用户。邀请管理 API 移除了 `used_at`、`used_by_user_id` 和 `revoked_at`,可通过注册记录和邀请状态查看使用情况。

‎src/octop/cli/commands/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
"""Click command modules (one file per top-level `octop` subcommand)."""
1+
"""Click command modules (one module per top-level `octop` subcommand)."""
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""Offline health checks (``octop doctor``).
2+
3+
Each check is a module in this package and is registered on ``doctor``.
4+
"""
5+
6+
from __future__ import annotations
7+
8+
import click
9+
10+
from octop.cli.commands.doctor.db import database
11+
12+
13+
@click.group()
14+
def doctor() -> None:
15+
"""Run offline health checks."""
16+
17+
18+
doctor.add_command(database)
Lines changed: 41 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Offline SQLite health inspection and recovery commands (``octop db``)."""
1+
"""SQLite health check for ``octop doctor db``."""
22

33
from __future__ import annotations
44

@@ -18,11 +18,6 @@
1818
from octop.infra.utils.paths import PathLayout
1919

2020

21-
@click.group()
22-
def db() -> None:
23-
"""Inspect and recover local SQLite databases under OCTOP_HOME."""
24-
25-
2621
def _format_mb(nbytes: int) -> str:
2722
return f"{nbytes / (1024 * 1024):.2f} MB"
2823

@@ -35,7 +30,7 @@ def _print_report(report: SqliteCheckReport) -> None:
3530
click.echo(f" {report.error}")
3631

3732

38-
@db.command(name="doctor")
33+
@click.command(name="db")
3934
@click.option(
4035
"--full",
4136
is_flag=True,
@@ -49,7 +44,36 @@ def _print_report(report: SqliteCheckReport) -> None:
4944
default=None,
5045
help="Check a single SQLite file instead of scanning OCTOP_HOME.",
5146
)
52-
def doctor(full: bool, target_path: Path | None) -> None:
47+
@click.option(
48+
"--fix",
49+
is_flag=True,
50+
default=False,
51+
help="Repair corrupted SQLite files after checking them.",
52+
)
53+
@click.option(
54+
"--reset",
55+
is_flag=True,
56+
default=False,
57+
help="Archive damaged databases and remove them so Octop recreates clean files.",
58+
)
59+
@click.option(
60+
"-y",
61+
"--yes",
62+
is_flag=True,
63+
default=False,
64+
help="Skip the interactive confirmation prompt when fixing databases.",
65+
)
66+
def database(full: bool, target_path: Path | None, fix: bool, reset: bool, yes: bool) -> None:
67+
"""Inspect local SQLite databases under OCTOP_HOME."""
68+
if not fix:
69+
if reset or yes:
70+
raise click.UsageError("--reset and --yes require --fix.")
71+
_check_databases(full, target_path)
72+
return
73+
_fix_databases(target_path, reset, yes)
74+
75+
76+
def _check_databases(full: bool, target_path: Path | None) -> None:
5377
"""Check SQLite databases under OCTOP_HOME for corruption."""
5478
paths = (
5579
[target_path]
@@ -80,8 +104,8 @@ def doctor(full: bool, target_path: Path | None) -> None:
80104
if corrupt:
81105
click.echo(
82106
f"\nFound {len(corrupt)} corrupted database(s). "
83-
"Stop Octop first, then run `octop db recover --all-corrupt` "
84-
"(or `octop db recover <path>`)."
107+
"Stop Octop first, then run `octop doctor db --fix` "
108+
"(or `octop doctor db --fix --path <path>`)."
85109
)
86110
else:
87111
click.echo(f"\nAll {len(reports)} SQLite database(s) passed integrity check.")
@@ -90,44 +114,17 @@ def doctor(full: bool, target_path: Path | None) -> None:
90114
raise click.exceptions.Exit(1)
91115

92116

93-
@db.command(name="recover")
94-
@click.argument("target", type=click.Path(path_type=Path), required=False, default=None)
95-
@click.option(
96-
"--all-corrupt",
97-
is_flag=True,
98-
default=False,
99-
help="Recover every SQLite file under OCTOP_HOME that fails PRAGMA quick_check.",
100-
)
101-
@click.option(
102-
"--reset",
103-
is_flag=True,
104-
default=False,
105-
help="Archive the damaged database and remove it so Octop recreates a clean file.",
106-
)
107-
@click.option(
108-
"-y",
109-
"--yes",
110-
is_flag=True,
111-
default=False,
112-
help="Skip the interactive confirmation prompt.",
113-
)
114-
def recover(target: Path | None, all_corrupt: bool, reset: bool, yes: bool) -> None:
115-
"""Back up and recover a corrupted SQLite file (stop Octop before running)."""
116-
if target is None and not all_corrupt:
117-
raise click.UsageError("Specify a database TARGET path or pass --all-corrupt.")
118-
if target is not None and all_corrupt:
119-
raise click.UsageError("Pass either TARGET or --all-corrupt, not both.")
120-
121-
if all_corrupt:
117+
def _fix_databases(target_path: Path | None, reset: bool, yes: bool) -> None:
118+
"""Back up and repair corrupted SQLite files under OCTOP_HOME."""
119+
if target_path is None:
122120
reports = [
123121
inspect_sqlite_file(p) for p in discover_sqlite_files(PathLayout.from_env().root)
124122
]
125123
targets = [Path(r.path) for r in reports if not r.ok]
126124
else:
127-
assert target is not None
128-
if not target.is_file():
129-
raise click.ClickException(f"SQLite file not found: {target}")
130-
targets = [target]
125+
if not target_path.is_file():
126+
raise click.ClickException(f"SQLite file not found: {target_path}")
127+
targets = [target_path]
131128

132129
if not targets:
133130
if json_output_enabled():
@@ -138,7 +135,7 @@ def recover(target: Path | None, all_corrupt: bool, reset: bool, yes: bool) -> N
138135

139136
mode: Literal["recover", "reset"] = "reset" if reset else "recover"
140137
if not yes:
141-
action = "archive and reset" if reset else "back up and recover"
138+
action = "archive and reset" if reset else "back up and fix"
142139
prompt = (
143140
f"Make sure the Octop server is stopped before modifying SQLite files.\n"
144141
f"Proceed to {action} {len(targets)} database file(s)?"

‎src/octop/cli/registry.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
"update": (".commands.update", "update", "Check for and install a newer Octop release."),
3333
"clean": (".commands.clean", "clean", "Remove CLI state or wipe all of ~/.octop."),
3434
"backup": (".commands.backup", "backup", "Export and restore Octop backups."),
35-
"db": (".commands.db", "db", "Inspect and recover local SQLite databases."),
35+
"doctor": (".commands.doctor", "doctor", "Offline health checks."),
3636
"bridge": (".commands.bridge", "bridge", "Manage remote Octop bridge peers."),
3737
"acp": (".commands.acp", "acp_cmd", "Run Octop agent as ACP server (stdio)."),
3838
"plugin": (".commands.plugin", "plugin", "Install and manage plugins."),

‎src/octop/i18n/en.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -836,7 +836,7 @@
836836
"model_call_failed_detail": "The model call failed: {detail}",
837837
"model_retry_prompt": "The model API request failed. Do not pretend the task succeeded.\n\nWhat happened: {guidance}\n\nExplain this to the user in their language and suggest the next step. Do not retry the same failing request unchanged.\n\nTechnical detail: {detail}",
838838
"path_outside_root": "The file path is outside this expert's storage root, so it cannot be read or written. Use a path under the storage root, or widen the storage root in expert settings (on Windows, set an explicit drive path such as D:/octop-data).",
839-
"database_corrupt": "A local SQLite database file appears corrupted (database disk image is malformed). This is not a model configuration issue. Stop Octop and run `octop db doctor` to locate the damaged file, then run `octop db recover` to repair it (see logs/octop.log for details)."
839+
"database_corrupt": "A local SQLite database file appears corrupted (database disk image is malformed). This is not a model configuration issue. Stop Octop and run `octop doctor db` to locate the damaged file, then run `octop doctor db --fix` to repair it (see logs/octop.log for details)."
840840
},
841841
"attachment": {
842842
"header": "[Attachment] {filename}",

‎src/octop/i18n/zh.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -836,7 +836,7 @@
836836
"model_call_failed_detail": "模型调用失败:{detail}",
837837
"model_retry_prompt": "模型接口调用失败,不要假装任务已经完成。\n\n原因:{guidance}\n\n请用用户的语言说明情况并给出下一步建议。不要用同样的请求再试一次。\n\n技术细节:{detail}",
838838
"path_outside_root": "文件路径超出当前专家的存储根目录,无法读写。请改用存储根目录内的路径,或在专家设置中扩大存储根目录(Windows 上请显式指定盘符路径,例如 D:/octop-data)。",
839-
"database_corrupt": "本地 SQLite 数据库文件已损坏(database disk image is malformed),并非模型配置问题。请先停止 Octop 服务,运行 `octop db doctor` 定位损坏库文件,再执行 `octop db recover` 修复(详见 logs/octop.log)。"
839+
"database_corrupt": "本地 SQLite 数据库文件已损坏(database disk image is malformed),并非模型配置问题。请先停止 Octop 服务,运行 `octop doctor db` 定位损坏库文件,再执行 `octop doctor db --fix` 修复(详见 logs/octop.log)。"
840840
},
841841
"attachment": {
842842
"header": "[附件] {filename}",

‎tests/unit/db/test_sqlite_doctor.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def test_recover_sqlite_file_reset_archives_and_removes_target(tmp_path: Path) -
127127
assert Path(result.backup_path).read_bytes() == b"broken"
128128

129129

130-
def test_cli_db_doctor_and_recover(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
130+
def test_cli_doctor_db_and_fix(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
131131
monkeypatch.setenv("OCTOP_HOME", str(tmp_path))
132132
healthy = tmp_path / "octop.db"
133133
corrupt = tmp_path / "agents" / "ag1" / ".octop" / "memory.sqlite"
@@ -136,20 +136,20 @@ def test_cli_db_doctor_and_recover(tmp_path: Path, monkeypatch: pytest.MonkeyPat
136136
corrupt.write_bytes(b"totally corrupted database")
137137

138138
runner = CliRunner()
139-
res = runner.invoke(cli, ["--json", "db", "doctor"])
139+
res = runner.invoke(cli, ["--json", "doctor", "db"])
140140
assert res.exit_code == 1, res.output
141141
payload = json.loads(res.output)
142142
assert payload["ok"] is False
143143
assert payload["checked"] == 2
144144
assert payload["corrupt"] == 1
145145

146-
reset_res = runner.invoke(cli, ["--json", "db", "recover", "--all-corrupt", "--reset", "--yes"])
146+
reset_res = runner.invoke(cli, ["--json", "doctor", "db", "--fix", "--reset", "--yes"])
147147
assert reset_res.exit_code == 0, reset_res.output
148148
rec_payload = json.loads(reset_res.output)
149149
assert len(rec_payload["recovered"]) == 1
150150
assert rec_payload["recovered"][0]["method"] == "reset"
151151
assert not corrupt.exists()
152152

153-
after = runner.invoke(cli, ["--json", "db", "doctor"])
153+
after = runner.invoke(cli, ["--json", "doctor", "db"])
154154
assert after.exit_code == 0, after.output
155155
assert json.loads(after.output)["ok"] is True

‎tests/unit/i18n/test_stream.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,11 +293,11 @@ def test_classify_and_format_sqlite_corruption() -> None:
293293
zh = format_stream_error(sqlite3.DatabaseError("database disk image is malformed"), "zh")
294294
assert "模型调用失败" not in zh
295295
assert "SQLite" in zh
296-
assert "octop db doctor" in zh
296+
assert "octop doctor db --fix" in zh
297297

298298
wrapped = RuntimeError("stream failed")
299299
wrapped.__cause__ = sqlite3.DatabaseError("database disk image is malformed")
300300
en = format_stream_error(wrapped, "en")
301301
assert "model call failed" not in en.lower()
302302
assert "SQLite" in en
303-
assert "octop db doctor" in en
303+
assert "octop doctor db --fix" in en

0 commit comments

Comments
 (0)