second-brain-keeper 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sbk/__init__.py +57 -0
- sbk/cli/commands/__init__.py +1 -0
- sbk/cli/commands/archive.py +45 -0
- sbk/cli/commands/attachments.py +42 -0
- sbk/cli/commands/audit.py +69 -0
- sbk/cli/commands/config.py +48 -0
- sbk/cli/commands/create.py +77 -0
- sbk/cli/commands/disambiguate.py +35 -0
- sbk/cli/commands/frontmatter.py +188 -0
- sbk/cli/commands/graph.py +86 -0
- sbk/cli/commands/history.py +55 -0
- sbk/cli/commands/indices.py +32 -0
- sbk/cli/commands/init.py +27 -0
- sbk/cli/commands/links.py +40 -0
- sbk/cli/commands/map.py +41 -0
- sbk/cli/commands/move.py +69 -0
- sbk/cli/commands/naming.py +36 -0
- sbk/cli/commands/offload.py +53 -0
- sbk/cli/commands/rename.py +93 -0
- sbk/cli/commands/search.py +70 -0
- sbk/cli/commands/tags.py +73 -0
- sbk/cli/commands/undo.py +37 -0
- sbk/cli/constants.py +16 -0
- sbk/cli/logging.py +108 -0
- sbk/cli/main.py +427 -0
- sbk/config.py +280 -0
- sbk/core/__init__.py +90 -0
- sbk/core/attachments.py +164 -0
- sbk/core/audit.py +278 -0
- sbk/core/document.py +182 -0
- sbk/core/frontmatter.py +359 -0
- sbk/core/graph.py +140 -0
- sbk/core/indices.py +358 -0
- sbk/core/journal.py +421 -0
- sbk/core/lifecycle.py +718 -0
- sbk/core/links.py +298 -0
- sbk/core/map.py +141 -0
- sbk/core/naming.py +212 -0
- sbk/core/search.py +171 -0
- sbk/core/taxonomy.py +256 -0
- sbk/core/templates.py +348 -0
- sbk/core/traversal.py +90 -0
- sbk/exceptions.py +96 -0
- sbk/models/__init__.py +68 -0
- sbk/models/config.py +99 -0
- sbk/models/entities.py +46 -0
- sbk/models/journal.py +94 -0
- sbk/models/results.py +92 -0
- sbk/models/telemetry.py +236 -0
- sbk/utils/__init__.py +13 -0
- sbk/utils/formatters.py +131 -0
- sbk/utils/helpers.py +41 -0
- sbk/vault.py +863 -0
- second_brain_keeper-1.1.1.dist-info/METADATA +233 -0
- second_brain_keeper-1.1.1.dist-info/RECORD +59 -0
- second_brain_keeper-1.1.1.dist-info/WHEEL +5 -0
- second_brain_keeper-1.1.1.dist-info/entry_points.txt +3 -0
- second_brain_keeper-1.1.1.dist-info/licenses/LICENSE +674 -0
- second_brain_keeper-1.1.1.dist-info/top_level.txt +1 -0
sbk/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""SBK (Second Brain Keeper): Universal Second Brain governance, link validator and maintenance toolkit."""
|
|
2
|
+
|
|
3
|
+
from .config import generate_default_config_content, load_vault_config
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
AttachmentError,
|
|
6
|
+
ConfigurationError,
|
|
7
|
+
CreationError,
|
|
8
|
+
FrontmatterError,
|
|
9
|
+
LinkResolutionError,
|
|
10
|
+
NamingError,
|
|
11
|
+
SBKError,
|
|
12
|
+
TaxonomyError,
|
|
13
|
+
TemplateError,
|
|
14
|
+
VaultKeeperError,
|
|
15
|
+
VaultNotFoundError,
|
|
16
|
+
)
|
|
17
|
+
from .models import (
|
|
18
|
+
AuditReport,
|
|
19
|
+
BrokenLink,
|
|
20
|
+
CreateResult,
|
|
21
|
+
Frontmatter,
|
|
22
|
+
Note,
|
|
23
|
+
OrphanAttachment,
|
|
24
|
+
PhaseResult,
|
|
25
|
+
VaultCatalog,
|
|
26
|
+
VaultConfig,
|
|
27
|
+
)
|
|
28
|
+
from .vault import Vault
|
|
29
|
+
|
|
30
|
+
__version__ = "1.1.1"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"__version__",
|
|
34
|
+
"Vault",
|
|
35
|
+
"VaultConfig",
|
|
36
|
+
"load_vault_config",
|
|
37
|
+
"generate_default_config_content",
|
|
38
|
+
"BrokenLink",
|
|
39
|
+
"CreateResult",
|
|
40
|
+
"Frontmatter",
|
|
41
|
+
"Note",
|
|
42
|
+
"OrphanAttachment",
|
|
43
|
+
"PhaseResult",
|
|
44
|
+
"AuditReport",
|
|
45
|
+
"VaultCatalog",
|
|
46
|
+
"SBKError",
|
|
47
|
+
"VaultKeeperError",
|
|
48
|
+
"ConfigurationError",
|
|
49
|
+
"VaultNotFoundError",
|
|
50
|
+
"CreationError",
|
|
51
|
+
"TemplateError",
|
|
52
|
+
"FrontmatterError",
|
|
53
|
+
"TaxonomyError",
|
|
54
|
+
"NamingError",
|
|
55
|
+
"LinkResolutionError",
|
|
56
|
+
"AttachmentError",
|
|
57
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""CLI command implementations for the vk entrypoint."""
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Implementation of 'sbk archive' command."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
|
|
6
|
+
from ...exceptions import ArchiveError, VaultKeeperError
|
|
7
|
+
from ...vault import Vault
|
|
8
|
+
from ..constants import EXIT_ERROR, EXIT_SUCCESS
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def handle_archive(args: Namespace, logger: logging.Logger) -> int:
|
|
12
|
+
"""Archive a note or project folder to mirror cold storage with Tombstone support."""
|
|
13
|
+
try:
|
|
14
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
15
|
+
except Exception as exc:
|
|
16
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
17
|
+
return EXIT_ERROR
|
|
18
|
+
|
|
19
|
+
target_arg = getattr(args, "target")
|
|
20
|
+
no_tombstone = getattr(args, "no_tombstone", False)
|
|
21
|
+
dry_run = getattr(args, "dry_run", False)
|
|
22
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
res = v.archive(
|
|
26
|
+
item_path=target_arg,
|
|
27
|
+
no_tombstone=no_tombstone,
|
|
28
|
+
dry_run=dry_run,
|
|
29
|
+
)
|
|
30
|
+
except (ArchiveError, VaultKeeperError) as exc:
|
|
31
|
+
logger.error("Archive rejected: %s", exc)
|
|
32
|
+
return EXIT_ERROR
|
|
33
|
+
except Exception as exc:
|
|
34
|
+
logger.error("Unexpected error during archive: %s", exc)
|
|
35
|
+
return EXIT_ERROR
|
|
36
|
+
|
|
37
|
+
logger.info("%sArchived: %s", prefix, res.source_path.name)
|
|
38
|
+
logger.info(" - Cold storage destination: %s", res.archive_path.as_posix())
|
|
39
|
+
logger.info(" - Tombstone note created: %s", "Yes" if res.tombstone_created else "No")
|
|
40
|
+
if res.summary:
|
|
41
|
+
logger.info(" - Preserved summary: %s", res.summary)
|
|
42
|
+
if res.tx_id:
|
|
43
|
+
logger.info(" - Transaction ID: %s (reversible with 'sbk undo')", res.tx_id)
|
|
44
|
+
|
|
45
|
+
return EXIT_SUCCESS
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Implementation of 'sbk clean-attachments' command."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
|
|
6
|
+
from ...utils.helpers import format_bytes
|
|
7
|
+
from ...vault import Vault
|
|
8
|
+
from ..constants import EXIT_ERROR, EXIT_SUCCESS
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def handle_attachments(args: Namespace, logger: logging.Logger) -> int:
|
|
12
|
+
"""Clean orphan attachments by moving them to .trash or hard-deleting."""
|
|
13
|
+
try:
|
|
14
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
15
|
+
except Exception as exc:
|
|
16
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
17
|
+
return EXIT_ERROR
|
|
18
|
+
|
|
19
|
+
dry_run = getattr(args, "dry_run", False)
|
|
20
|
+
hard_delete = getattr(args, "hard_delete", False)
|
|
21
|
+
target = getattr(args, "target", None)
|
|
22
|
+
|
|
23
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
24
|
+
action_name = "Hard delete" if hard_delete else "Soft delete to .trash"
|
|
25
|
+
|
|
26
|
+
logger.info("%sExecuting attachment cleanup in: %s", prefix, v.root)
|
|
27
|
+
orphans = v.find_orphans(target=target)
|
|
28
|
+
|
|
29
|
+
if not orphans:
|
|
30
|
+
logger.info("No orphan attachments found.")
|
|
31
|
+
return EXIT_SUCCESS
|
|
32
|
+
|
|
33
|
+
logger.info("Found %d orphan attachments:", len(orphans))
|
|
34
|
+
total_bytes = sum(o.size_bytes for o in orphans)
|
|
35
|
+
for o in orphans:
|
|
36
|
+
logger.info(" - %s (%s)", o.rel_path.as_posix(), format_bytes(o.size_bytes))
|
|
37
|
+
|
|
38
|
+
results = v.clean_attachments(target=target, hard_delete=hard_delete, dry_run=dry_run)
|
|
39
|
+
logger.info(
|
|
40
|
+
"%sCompleted %s for %d files (Total space: %s).", prefix, action_name, len(results), format_bytes(total_bytes)
|
|
41
|
+
)
|
|
42
|
+
return EXIT_SUCCESS
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Implementation of 'sbk audit' command."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from argparse import Namespace
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ...vault import Vault
|
|
9
|
+
from ..constants import EXIT_ERROR, EXIT_ISSUES_FOUND, EXIT_SUCCESS
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def handle_audit(args: Namespace, logger: logging.Logger) -> int:
|
|
13
|
+
"""Execute unified multi-phase audit and format results."""
|
|
14
|
+
try:
|
|
15
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
16
|
+
except Exception as exc:
|
|
17
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
18
|
+
return EXIT_ERROR
|
|
19
|
+
|
|
20
|
+
steps = [int(args.step)] if getattr(args, "step", None) else [1, 2, 3, 4, 5]
|
|
21
|
+
logger.info("Executing VaultKeeper audit for: %s", v.root)
|
|
22
|
+
logger.info("Phases to execute: %s", ", ".join(str(s) for s in steps))
|
|
23
|
+
|
|
24
|
+
report = v.audit(phases=steps)
|
|
25
|
+
|
|
26
|
+
logger.info("-" * 60)
|
|
27
|
+
for phase in report.phases:
|
|
28
|
+
status_text = "OK" if phase.is_clean() else f"{len(phase.issues)} ISSUES"
|
|
29
|
+
logger.info("[Phase %d] %s: %s (%d warnings)", phase.phase_id, phase.title, status_text, len(phase.warnings))
|
|
30
|
+
for issue in phase.issues[:10]:
|
|
31
|
+
logger.warning(" - %s", issue)
|
|
32
|
+
if len(phase.issues) > 10:
|
|
33
|
+
logger.warning(" ... and %d more issues", len(phase.issues) - 10)
|
|
34
|
+
|
|
35
|
+
logger.info("-" * 60)
|
|
36
|
+
logger.info("Total Issues: %d", report.total_issues)
|
|
37
|
+
logger.info("Vault Health Score: %.2f / 100.0", report.health_score)
|
|
38
|
+
|
|
39
|
+
# Export JSON if requested
|
|
40
|
+
if getattr(args, "json", None):
|
|
41
|
+
out_json = Path(args.json).resolve()
|
|
42
|
+
out_json.write_text(json.dumps(report.to_dict(), indent=2), encoding="utf-8")
|
|
43
|
+
logger.info("Saved JSON audit report to: %s", out_json)
|
|
44
|
+
|
|
45
|
+
# Export Markdown if requested
|
|
46
|
+
if getattr(args, "report_md", None):
|
|
47
|
+
out_md = Path(args.report_md).resolve()
|
|
48
|
+
md_lines = [
|
|
49
|
+
f"# Audit Report - {report.vault_root.name}",
|
|
50
|
+
f"**Timestamp:** {report.timestamp}",
|
|
51
|
+
f"**Health Score:** {report.health_score:.2f} / 100.0",
|
|
52
|
+
f"**Total Issues:** {report.total_issues}",
|
|
53
|
+
"",
|
|
54
|
+
]
|
|
55
|
+
for phase in report.phases:
|
|
56
|
+
md_lines.append(f"## Phase {phase.phase_id}: {phase.title}")
|
|
57
|
+
md_lines.append(f"- Issues: {len(phase.issues)}")
|
|
58
|
+
md_lines.append(f"- Warnings: {len(phase.warnings)}")
|
|
59
|
+
if phase.issues:
|
|
60
|
+
md_lines.append("")
|
|
61
|
+
md_lines.append("### Issues")
|
|
62
|
+
for iss in phase.issues:
|
|
63
|
+
md_lines.append(f"- {iss}")
|
|
64
|
+
md_lines.append("")
|
|
65
|
+
|
|
66
|
+
out_md.write_text("\n".join(md_lines), encoding="utf-8")
|
|
67
|
+
logger.info("Saved Markdown audit report to: %s", out_md)
|
|
68
|
+
|
|
69
|
+
return EXIT_SUCCESS if report.is_clean() else EXIT_ISSUES_FOUND
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Implementation of 'sbk config' command: show, set."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
|
|
6
|
+
from ...exceptions import ConfigurationError, VaultKeeperError
|
|
7
|
+
from ...utils.formatters import format_output
|
|
8
|
+
from ...vault import Vault
|
|
9
|
+
from ..constants import EXIT_ERROR, EXIT_SUCCESS
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def handle_config(args: Namespace, logger: logging.Logger) -> int:
|
|
13
|
+
"""Inspect and update vault configuration directives."""
|
|
14
|
+
try:
|
|
15
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
16
|
+
except Exception as exc:
|
|
17
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
18
|
+
return EXIT_ERROR
|
|
19
|
+
|
|
20
|
+
action = getattr(args, "config_action", None)
|
|
21
|
+
if not action:
|
|
22
|
+
logger.error("No config action specified. Choose from: show, set.")
|
|
23
|
+
return EXIT_ERROR
|
|
24
|
+
|
|
25
|
+
if action == "show":
|
|
26
|
+
fmt = getattr(args, "format", "yaml")
|
|
27
|
+
cfg_dict = v.config_show()
|
|
28
|
+
rendered = format_output(cfg_dict, format=fmt, title="Vault Configuration")
|
|
29
|
+
print(rendered)
|
|
30
|
+
return EXIT_SUCCESS
|
|
31
|
+
|
|
32
|
+
if action == "set":
|
|
33
|
+
key = getattr(args, "key")
|
|
34
|
+
value = getattr(args, "value")
|
|
35
|
+
dry_run = getattr(args, "dry_run", False)
|
|
36
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
v.config_set(key=key, value=value, dry_run=dry_run)
|
|
40
|
+
except (ConfigurationError, VaultKeeperError) as exc:
|
|
41
|
+
logger.error("Failed to set configuration: %s", exc)
|
|
42
|
+
return EXIT_ERROR
|
|
43
|
+
|
|
44
|
+
logger.info("%sConfiguration updated: %s = %s", prefix, key, value)
|
|
45
|
+
return EXIT_SUCCESS
|
|
46
|
+
|
|
47
|
+
logger.error("Unknown config action: %s", action)
|
|
48
|
+
return EXIT_ERROR
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Implementation of 'sbk create' command."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
from ...exceptions import CreationError, TaxonomyError, TemplateError, VaultKeeperError
|
|
8
|
+
from ...utils.formatters import format_output, render_markdown_table
|
|
9
|
+
from ...vault import Vault
|
|
10
|
+
from ..constants import EXIT_ERROR, EXIT_SUCCESS
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def handle_create(args: Namespace, logger: logging.Logger) -> int:
|
|
14
|
+
"""Create a standardized note using templates, strict validation, and folder auto-routing."""
|
|
15
|
+
try:
|
|
16
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
17
|
+
except Exception as exc:
|
|
18
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
19
|
+
return EXIT_ERROR
|
|
20
|
+
|
|
21
|
+
title = getattr(args, "title")
|
|
22
|
+
tipo = getattr(args, "tipo")
|
|
23
|
+
folder = getattr(args, "folder", None)
|
|
24
|
+
raw_tags = getattr(args, "tags", None)
|
|
25
|
+
template = getattr(args, "template", None)
|
|
26
|
+
dry_run = getattr(args, "dry_run", False)
|
|
27
|
+
fmt = getattr(args, "format", "md")
|
|
28
|
+
|
|
29
|
+
tags_list: Optional[List[str]] = None
|
|
30
|
+
if raw_tags:
|
|
31
|
+
tags_list = [t.strip().lstrip("#") for t in raw_tags.split(",") if t.strip()]
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
res = v.create(
|
|
35
|
+
title=title,
|
|
36
|
+
tipo=tipo,
|
|
37
|
+
folder=folder,
|
|
38
|
+
tags=tags_list,
|
|
39
|
+
template=template,
|
|
40
|
+
dry_run=dry_run,
|
|
41
|
+
)
|
|
42
|
+
except (CreationError, TaxonomyError, TemplateError, VaultKeeperError) as exc:
|
|
43
|
+
logger.error("Creation failed: %s", exc)
|
|
44
|
+
return EXIT_ERROR
|
|
45
|
+
except Exception as exc:
|
|
46
|
+
logger.error("Unexpected error during note creation: %s", exc)
|
|
47
|
+
return EXIT_ERROR
|
|
48
|
+
|
|
49
|
+
if fmt in ("json", "yaml", "csv"):
|
|
50
|
+
print(format_output(res, format=fmt))
|
|
51
|
+
return EXIT_SUCCESS
|
|
52
|
+
|
|
53
|
+
# Markdown format
|
|
54
|
+
idx_info = f"Aggiornato (`{res.index_path.name}`)" if res.index_updated and res.index_path else "Invariato"
|
|
55
|
+
status_info = (
|
|
56
|
+
"[DRY-RUN] Nessun file scritto"
|
|
57
|
+
if res.dry_run
|
|
58
|
+
else f"Transazione `{res.tx_id or 'N/A'}` (annullabile con `vk undo`)"
|
|
59
|
+
)
|
|
60
|
+
tags_str = ", ".join(f"`{t}`" for t in res.tags) if res.tags else "(Nessuno)"
|
|
61
|
+
|
|
62
|
+
table = render_markdown_table(
|
|
63
|
+
headers=["Proprietà", "Valore"],
|
|
64
|
+
rows=[
|
|
65
|
+
["Percorso", f"`{res.rel_path.as_posix()}`"],
|
|
66
|
+
["Stem", f"[[{res.stem}]]"],
|
|
67
|
+
["Tipo", f"`{res.tipo}`"],
|
|
68
|
+
["Tag", tags_str],
|
|
69
|
+
["Template", f"`{res.template_used or 'Predefinito Standard'}`"],
|
|
70
|
+
["Indice Cartella", idx_info],
|
|
71
|
+
["Stato", status_info],
|
|
72
|
+
],
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
prefix = "[DRY-RUN] " if res.dry_run else ""
|
|
76
|
+
print(f"# {prefix}Nuova Nota: {res.title}\n\n{table}")
|
|
77
|
+
return EXIT_SUCCESS
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Implementation of 'sbk disambiguate' command."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
|
|
6
|
+
from ...vault import Vault
|
|
7
|
+
from ..constants import EXIT_ERROR, EXIT_ISSUES_FOUND, EXIT_SUCCESS
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def handle_disambiguate(args: Namespace, logger: logging.Logger) -> int:
|
|
11
|
+
"""Scan and report stem collisions between notes located in separate folders."""
|
|
12
|
+
try:
|
|
13
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
14
|
+
except Exception as exc:
|
|
15
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
16
|
+
return EXIT_ERROR
|
|
17
|
+
|
|
18
|
+
collisions = v.stem_collisions()
|
|
19
|
+
|
|
20
|
+
if not collisions:
|
|
21
|
+
logger.info("No stem collisions detected across vault.")
|
|
22
|
+
return EXIT_SUCCESS
|
|
23
|
+
|
|
24
|
+
logger.warning("Detected %d stem collisions:", len(collisions))
|
|
25
|
+
for stem, paths in collisions.items():
|
|
26
|
+
logger.warning(" - '%s' is duplicated across %d paths:", stem, len(paths))
|
|
27
|
+
for p in paths:
|
|
28
|
+
try:
|
|
29
|
+
rel = p.relative_to(v.root).as_posix()
|
|
30
|
+
except ValueError:
|
|
31
|
+
rel = str(p)
|
|
32
|
+
logger.warning(" * %s", rel)
|
|
33
|
+
|
|
34
|
+
logger.info("Recommendation: Rename duplicated notes with contextual prefixes or use 'sbk normalize-names'.")
|
|
35
|
+
return EXIT_ISSUES_FOUND
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Implementation of 'sbk frontmatter' subcommands."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from ...core.frontmatter import (
|
|
8
|
+
parse_note_content,
|
|
9
|
+
update_frontmatter,
|
|
10
|
+
)
|
|
11
|
+
from ...core.traversal import walk_vault_files
|
|
12
|
+
from ...exceptions import FrontmatterError, VaultKeeperError
|
|
13
|
+
from ...vault import Vault
|
|
14
|
+
from ..constants import EXIT_ERROR, EXIT_SUCCESS
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def handle_frontmatter(args: Namespace, logger: logging.Logger) -> int:
|
|
18
|
+
"""Dispatch frontmatter subcommands."""
|
|
19
|
+
subaction = getattr(args, "fm_action", None)
|
|
20
|
+
if subaction == "set-type":
|
|
21
|
+
return handle_set_type(args, logger)
|
|
22
|
+
elif subaction == "add-tags":
|
|
23
|
+
return handle_add_tags(args, logger)
|
|
24
|
+
elif subaction == "sanitize-tags":
|
|
25
|
+
return handle_sanitize_tags(args, logger)
|
|
26
|
+
else:
|
|
27
|
+
logger.error("Unknown frontmatter action. Choose: set-type, add-tags, sanitize-tags.")
|
|
28
|
+
return EXIT_ERROR
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def handle_set_type(args: Namespace, logger: logging.Logger) -> int:
|
|
32
|
+
"""Set or update the tipo YAML frontmatter field."""
|
|
33
|
+
try:
|
|
34
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
35
|
+
except Exception as exc:
|
|
36
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
37
|
+
return EXIT_ERROR
|
|
38
|
+
|
|
39
|
+
batch_arg = getattr(args, "batch", None)
|
|
40
|
+
target = getattr(args, "target", None)
|
|
41
|
+
new_type = getattr(args, "type", None)
|
|
42
|
+
dry_run = getattr(args, "dry_run", False)
|
|
43
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
44
|
+
|
|
45
|
+
if batch_arg:
|
|
46
|
+
try:
|
|
47
|
+
results = v.batch_set_frontmatter_type(batch_arg, dry_run=dry_run)
|
|
48
|
+
except (FrontmatterError, VaultKeeperError) as exc:
|
|
49
|
+
logger.error("Batch set-type rejected: %s", exc)
|
|
50
|
+
return EXIT_ERROR
|
|
51
|
+
except Exception as exc:
|
|
52
|
+
logger.error("Unexpected error during batch set-type: %s", exc)
|
|
53
|
+
return EXIT_ERROR
|
|
54
|
+
|
|
55
|
+
updated_count = 0
|
|
56
|
+
for p, changed in results:
|
|
57
|
+
if changed:
|
|
58
|
+
logger.info("%sUpdated %s: set %s to '%s'", prefix, p.name, v.config.type_field, new_type or "new type")
|
|
59
|
+
updated_count += 1
|
|
60
|
+
else:
|
|
61
|
+
logger.info("%sUnchanged: %s already has target %s", prefix, p.name, v.config.type_field)
|
|
62
|
+
|
|
63
|
+
logger.info(
|
|
64
|
+
"%sBatch set-type completed successfully: %d processed, %d updated.",
|
|
65
|
+
prefix,
|
|
66
|
+
len(results),
|
|
67
|
+
updated_count,
|
|
68
|
+
)
|
|
69
|
+
return EXIT_SUCCESS
|
|
70
|
+
|
|
71
|
+
if not target or not new_type:
|
|
72
|
+
logger.error("Specify both --target and --type, or use --batch <file.json>.")
|
|
73
|
+
return EXIT_ERROR
|
|
74
|
+
|
|
75
|
+
target_path = Path(target).resolve()
|
|
76
|
+
changed = v.set_frontmatter_type(target_path, new_type, dry_run=dry_run)
|
|
77
|
+
|
|
78
|
+
if changed:
|
|
79
|
+
logger.info("%sUpdated %s: %s -> %s", prefix, target_path.name, v.config.type_field, new_type)
|
|
80
|
+
else:
|
|
81
|
+
logger.info("Frontmatter already has %s: %s", v.config.type_field, new_type)
|
|
82
|
+
|
|
83
|
+
return EXIT_SUCCESS
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def handle_add_tags(args: Namespace, logger: logging.Logger) -> int:
|
|
87
|
+
"""Inject or overwrite tags in a note's frontmatter."""
|
|
88
|
+
try:
|
|
89
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
90
|
+
except Exception as exc:
|
|
91
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
92
|
+
return EXIT_ERROR
|
|
93
|
+
|
|
94
|
+
batch_arg = getattr(args, "batch", None)
|
|
95
|
+
target = getattr(args, "target", None)
|
|
96
|
+
tags = getattr(args, "tags", None)
|
|
97
|
+
overwrite = getattr(args, "overwrite", False)
|
|
98
|
+
dry_run = getattr(args, "dry_run", False)
|
|
99
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
100
|
+
|
|
101
|
+
if batch_arg:
|
|
102
|
+
try:
|
|
103
|
+
results = v.batch_add_frontmatter_tags(batch_arg, overwrite=overwrite, dry_run=dry_run)
|
|
104
|
+
except (FrontmatterError, VaultKeeperError) as exc:
|
|
105
|
+
logger.error("Batch add-tags rejected: %s", exc)
|
|
106
|
+
return EXIT_ERROR
|
|
107
|
+
except Exception as exc:
|
|
108
|
+
logger.error("Unexpected error during batch add-tags: %s", exc)
|
|
109
|
+
return EXIT_ERROR
|
|
110
|
+
|
|
111
|
+
action_name = "overwritten" if overwrite else "added"
|
|
112
|
+
updated_count = 0
|
|
113
|
+
for p, changed in results:
|
|
114
|
+
if changed:
|
|
115
|
+
logger.info("%sUpdated %s: tags %s", prefix, p.name, action_name)
|
|
116
|
+
updated_count += 1
|
|
117
|
+
else:
|
|
118
|
+
logger.info("%sUnchanged: %s already contains specified tags", prefix, p.name)
|
|
119
|
+
|
|
120
|
+
logger.info(
|
|
121
|
+
"%sBatch %s completed successfully: %d processed, %d updated.",
|
|
122
|
+
prefix,
|
|
123
|
+
"overwrite-tags" if overwrite else "add-tags",
|
|
124
|
+
len(results),
|
|
125
|
+
updated_count,
|
|
126
|
+
)
|
|
127
|
+
return EXIT_SUCCESS
|
|
128
|
+
|
|
129
|
+
if not target or not tags:
|
|
130
|
+
logger.error("Specify both --target and --tags, or use --batch <file.json>.")
|
|
131
|
+
return EXIT_ERROR
|
|
132
|
+
|
|
133
|
+
target_path = Path(target).resolve()
|
|
134
|
+
changed = v.add_frontmatter_tags(target_path, tags, overwrite=overwrite, dry_run=dry_run)
|
|
135
|
+
|
|
136
|
+
if changed:
|
|
137
|
+
logger.info("%sInjected %d tags into: %s", prefix, len(tags), target_path.name)
|
|
138
|
+
else:
|
|
139
|
+
logger.info("Tags already present in: %s", target_path.name)
|
|
140
|
+
|
|
141
|
+
return EXIT_SUCCESS
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def handle_sanitize_tags(args: Namespace, logger: logging.Logger) -> int:
|
|
145
|
+
"""Sanitize and apply tag replacements based on taxonomy and config mapping."""
|
|
146
|
+
try:
|
|
147
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
148
|
+
except Exception as exc:
|
|
149
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
150
|
+
return EXIT_ERROR
|
|
151
|
+
|
|
152
|
+
dry_run = getattr(args, "dry_run", False)
|
|
153
|
+
target = getattr(args, "target", None)
|
|
154
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
155
|
+
|
|
156
|
+
target_dir = Path(target).resolve() if target else v.root
|
|
157
|
+
replacements = v.config.tag_replacements
|
|
158
|
+
logger.info("%sSanitizing tags across notes in: %s", prefix, target_dir)
|
|
159
|
+
|
|
160
|
+
modified_count = 0
|
|
161
|
+
for note_path in walk_vault_files(v.config, target_dir=target_dir, extensions={".md"}):
|
|
162
|
+
try:
|
|
163
|
+
content = note_path.read_text(encoding="utf-8")
|
|
164
|
+
except Exception:
|
|
165
|
+
continue
|
|
166
|
+
|
|
167
|
+
fm, body = parse_note_content(content, type_field=v.config.type_field)
|
|
168
|
+
if not fm or not fm.tags:
|
|
169
|
+
continue
|
|
170
|
+
|
|
171
|
+
updated_tags = []
|
|
172
|
+
changed = False
|
|
173
|
+
for tag in fm.tags:
|
|
174
|
+
if tag in replacements:
|
|
175
|
+
updated_tags.append(replacements[tag])
|
|
176
|
+
changed = True
|
|
177
|
+
else:
|
|
178
|
+
updated_tags.append(tag)
|
|
179
|
+
|
|
180
|
+
if changed:
|
|
181
|
+
updated_content = update_frontmatter(content, {"tags": updated_tags}, type_field=v.config.type_field)
|
|
182
|
+
if not dry_run:
|
|
183
|
+
note_path.write_text(updated_content, encoding="utf-8")
|
|
184
|
+
modified_count += 1
|
|
185
|
+
logger.info(" - %s: updated tags to %s", note_path.name, updated_tags)
|
|
186
|
+
|
|
187
|
+
logger.info("%sCompleted tag sanitization. %d notes modified.", prefix, modified_count)
|
|
188
|
+
return EXIT_SUCCESS
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Implementation of 'sbk graph-health' command."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
|
|
6
|
+
from ...exceptions import SBKError, VaultKeeperError
|
|
7
|
+
from ...utils.formatters import format_output
|
|
8
|
+
from ...vault import Vault
|
|
9
|
+
from ..constants import EXIT_ERROR, EXIT_SUCCESS
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def handle_graph_health(args: Namespace, logger: logging.Logger) -> int:
|
|
13
|
+
"""Execute non-punitive topological graph analysis."""
|
|
14
|
+
try:
|
|
15
|
+
v = Vault(root_path=getattr(args, "root", None), config_file=getattr(args, "config", None))
|
|
16
|
+
except Exception as exc:
|
|
17
|
+
logger.error("Failed to initialize vault: %s", exc)
|
|
18
|
+
return EXIT_ERROR
|
|
19
|
+
|
|
20
|
+
fmt = getattr(args, "format", "md")
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
report = v.graph_health()
|
|
24
|
+
except (SBKError, VaultKeeperError) as exc:
|
|
25
|
+
logger.error("Graph telemetry failed: %s", exc)
|
|
26
|
+
return EXIT_ERROR
|
|
27
|
+
|
|
28
|
+
if fmt == "md":
|
|
29
|
+
lines = [
|
|
30
|
+
"# Diagnostica Topologica del Grafo Concettuale",
|
|
31
|
+
"",
|
|
32
|
+
"> [!NOTE] Diagnostica Non-Punitiva",
|
|
33
|
+
"> I valori riportati hanno scopo puramente informativo ed esplorativo.",
|
|
34
|
+
"> Nessuna penalita' viene applicata al Vault Health Score di audit.",
|
|
35
|
+
"",
|
|
36
|
+
f"- **Totale Nodi (Note):** {report.total_nodes}",
|
|
37
|
+
f"- **Totale Archi (Collegamenti):** {report.total_edges}",
|
|
38
|
+
f"- **Note Isolate (True Orphans):** {len(report.true_orphans)}",
|
|
39
|
+
f"- **Vicoli Ciechi (Dead-Ends):** {len(report.dead_ends)}",
|
|
40
|
+
f"- **Componenti Disconnesse (<=3 note):** {len(report.disconnected_components)}",
|
|
41
|
+
"",
|
|
42
|
+
"## Top 10 Note Piu' Collegate (Hub)",
|
|
43
|
+
"",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
if report.top_hubs:
|
|
47
|
+
hub_rows = [
|
|
48
|
+
{
|
|
49
|
+
"Nota": f"[[{h.stem}]]",
|
|
50
|
+
"Backlink in Ingresso": h.in_degree,
|
|
51
|
+
"Link in Uscita": h.out_degree,
|
|
52
|
+
}
|
|
53
|
+
for h in report.top_hubs
|
|
54
|
+
]
|
|
55
|
+
lines.append(
|
|
56
|
+
format_output(
|
|
57
|
+
hub_rows,
|
|
58
|
+
format="md",
|
|
59
|
+
headers=["Nota", "Backlink in Ingresso", "Link in Uscita"],
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
else:
|
|
63
|
+
lines.append("*(Nessun hub rilevato con collegamenti in ingresso)*")
|
|
64
|
+
|
|
65
|
+
lines.extend(["", "## Note Isolate (Senza link ne' indice)", ""])
|
|
66
|
+
if report.true_orphans:
|
|
67
|
+
for o in report.true_orphans:
|
|
68
|
+
lines.append(f"- [[{o}]]")
|
|
69
|
+
else:
|
|
70
|
+
lines.append("*(Nessuna nota totalmente orfana rilevata)*")
|
|
71
|
+
|
|
72
|
+
lines.extend(["", "## Vicoli Ciechi (Zero link uscenti)", ""])
|
|
73
|
+
if report.dead_ends:
|
|
74
|
+
for de in report.dead_ends[:20]:
|
|
75
|
+
lines.append(f"- [[{de}]]")
|
|
76
|
+
if len(report.dead_ends) > 20:
|
|
77
|
+
lines.append(f"*... e altri {len(report.dead_ends) - 20} vicoli ciechi*")
|
|
78
|
+
else:
|
|
79
|
+
lines.append("*(Nessun vicolo cieco rilevato)*")
|
|
80
|
+
|
|
81
|
+
print("\n".join(lines))
|
|
82
|
+
else:
|
|
83
|
+
rendered = format_output(report.to_dict(), format=fmt)
|
|
84
|
+
print(rendered)
|
|
85
|
+
|
|
86
|
+
return EXIT_SUCCESS
|