Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
## [Unreleased]

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

Each check is a module in this package and is registered on ``doctor``.
"""

from __future__ import annotations

import click

from octop.cli.commands.doctor.db import database


@click.group()
def doctor() -> None:
"""Run offline health checks."""


doctor.add_command(database)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Offline SQLite health inspection and recovery commands (``octop db``)."""
"""SQLite health check for ``octop doctor db``."""

from __future__ import annotations

Expand All @@ -18,11 +18,6 @@
from octop.infra.utils.paths import PathLayout


@click.group()
def db() -> None:
"""Inspect and recover local SQLite databases under OCTOP_HOME."""


def _format_mb(nbytes: int) -> str:
return f"{nbytes / (1024 * 1024):.2f} MB"

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


@db.command(name="doctor")
@click.command(name="db")
@click.option(
"--full",
is_flag=True,
Expand All @@ -49,7 +44,36 @@ def _print_report(report: SqliteCheckReport) -> None:
default=None,
help="Check a single SQLite file instead of scanning OCTOP_HOME.",
)
def doctor(full: bool, target_path: Path | None) -> None:
@click.option(
"--fix",
is_flag=True,
default=False,
help="Repair corrupted SQLite files after checking them.",
)
@click.option(
"--reset",
is_flag=True,
default=False,
help="Archive damaged databases and remove them so Octop recreates clean files.",
)
@click.option(
"-y",
"--yes",
is_flag=True,
default=False,
help="Skip the interactive confirmation prompt when fixing databases.",
)
def database(full: bool, target_path: Path | None, fix: bool, reset: bool, yes: bool) -> None:
"""Inspect local SQLite databases under OCTOP_HOME."""
if not fix:
if reset or yes:
raise click.UsageError("--reset and --yes require --fix.")
_check_databases(full, target_path)
return
_fix_databases(target_path, reset, yes)


def _check_databases(full: bool, target_path: Path | None) -> None:
"""Check SQLite databases under OCTOP_HOME for corruption."""
paths = (
[target_path]
Expand Down Expand Up @@ -80,8 +104,8 @@ def doctor(full: bool, target_path: Path | None) -> None:
if corrupt:
click.echo(
f"\nFound {len(corrupt)} corrupted database(s). "
"Stop Octop first, then run `octop db recover --all-corrupt` "
"(or `octop db recover <path>`)."
"Stop Octop first, then run `octop doctor db --fix` "
"(or `octop doctor db --fix --path <path>`)."
)
else:
click.echo(f"\nAll {len(reports)} SQLite database(s) passed integrity check.")
Expand All @@ -90,44 +114,17 @@ def doctor(full: bool, target_path: Path | None) -> None:
raise click.exceptions.Exit(1)


@db.command(name="recover")
@click.argument("target", type=click.Path(path_type=Path), required=False, default=None)
@click.option(
"--all-corrupt",
is_flag=True,
default=False,
help="Recover every SQLite file under OCTOP_HOME that fails PRAGMA quick_check.",
)
@click.option(
"--reset",
is_flag=True,
default=False,
help="Archive the damaged database and remove it so Octop recreates a clean file.",
)
@click.option(
"-y",
"--yes",
is_flag=True,
default=False,
help="Skip the interactive confirmation prompt.",
)
def recover(target: Path | None, all_corrupt: bool, reset: bool, yes: bool) -> None:
"""Back up and recover a corrupted SQLite file (stop Octop before running)."""
if target is None and not all_corrupt:
raise click.UsageError("Specify a database TARGET path or pass --all-corrupt.")
if target is not None and all_corrupt:
raise click.UsageError("Pass either TARGET or --all-corrupt, not both.")

if all_corrupt:
def _fix_databases(target_path: Path | None, reset: bool, yes: bool) -> None:
"""Back up and repair corrupted SQLite files under OCTOP_HOME."""
if target_path is None:
reports = [
inspect_sqlite_file(p) for p in discover_sqlite_files(PathLayout.from_env().root)
]
targets = [Path(r.path) for r in reports if not r.ok]
else:
assert target is not None
if not target.is_file():
raise click.ClickException(f"SQLite file not found: {target}")
targets = [target]
if not target_path.is_file():
raise click.ClickException(f"SQLite file not found: {target_path}")
targets = [target_path]

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

mode: Literal["recover", "reset"] = "reset" if reset else "recover"
if not yes:
action = "archive and reset" if reset else "back up and recover"
action = "archive and reset" if reset else "back up and fix"
prompt = (
f"Make sure the Octop server is stopped before modifying SQLite files.\n"
f"Proceed to {action} {len(targets)} database file(s)?"
Expand Down
2 changes: 1 addition & 1 deletion src/octop/cli/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"update": (".commands.update", "update", "Check for and install a newer Octop release."),
"clean": (".commands.clean", "clean", "Remove CLI state or wipe all of ~/.octop."),
"backup": (".commands.backup", "backup", "Export and restore Octop backups."),
"db": (".commands.db", "db", "Inspect and recover local SQLite databases."),
"doctor": (".commands.doctor", "doctor", "Offline health checks."),
"bridge": (".commands.bridge", "bridge", "Manage remote Octop bridge peers."),
"acp": (".commands.acp", "acp_cmd", "Run Octop agent as ACP server (stdio)."),
"plugin": (".commands.plugin", "plugin", "Install and manage plugins."),
Expand Down
2 changes: 1 addition & 1 deletion src/octop/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,7 @@
"model_call_failed_detail": "The model call failed: {detail}",
"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}",
"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).",
"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)."
"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)."
},
"attachment": {
"header": "[Attachment] {filename}",
Expand Down
2 changes: 1 addition & 1 deletion src/octop/i18n/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,7 @@
"model_call_failed_detail": "模型调用失败:{detail}",
"model_retry_prompt": "模型接口调用失败,不要假装任务已经完成。\n\n原因:{guidance}\n\n请用用户的语言说明情况并给出下一步建议。不要用同样的请求再试一次。\n\n技术细节:{detail}",
"path_outside_root": "文件路径超出当前专家的存储根目录,无法读写。请改用存储根目录内的路径,或在专家设置中扩大存储根目录(Windows 上请显式指定盘符路径,例如 D:/octop-data)。",
"database_corrupt": "本地 SQLite 数据库文件已损坏(database disk image is malformed),并非模型配置问题。请先停止 Octop 服务,运行 `octop db doctor` 定位损坏库文件,再执行 `octop db recover` 修复(详见 logs/octop.log)。"
"database_corrupt": "本地 SQLite 数据库文件已损坏(database disk image is malformed),并非模型配置问题。请先停止 Octop 服务,运行 `octop doctor db` 定位损坏库文件,再执行 `octop doctor db --fix` 修复(详见 logs/octop.log)。"
},
"attachment": {
"header": "[附件] {filename}",
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/db/test_sqlite_doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_recover_sqlite_file_reset_archives_and_removes_target(tmp_path: Path) -
assert Path(result.backup_path).read_bytes() == b"broken"


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

runner = CliRunner()
res = runner.invoke(cli, ["--json", "db", "doctor"])
res = runner.invoke(cli, ["--json", "doctor", "db"])
assert res.exit_code == 1, res.output
payload = json.loads(res.output)
assert payload["ok"] is False
assert payload["checked"] == 2
assert payload["corrupt"] == 1

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

after = runner.invoke(cli, ["--json", "db", "doctor"])
after = runner.invoke(cli, ["--json", "doctor", "db"])
assert after.exit_code == 0, after.output
assert json.loads(after.output)["ok"] is True
4 changes: 2 additions & 2 deletions tests/unit/i18n/test_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,11 +293,11 @@ def test_classify_and_format_sqlite_corruption() -> None:
zh = format_stream_error(sqlite3.DatabaseError("database disk image is malformed"), "zh")
assert "模型调用失败" not in zh
assert "SQLite" in zh
assert "octop db doctor" in zh
assert "octop doctor db --fix" in zh

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