task-ledger 1.3.27 → 1.3.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +4 -2
  2. package/SKILL.md +5 -3
  3. package/assets/worklog.md +1 -1
  4. package/package.json +1 -1
  5. package/references/init-identity.md +3 -3
  6. package/references/log-note.md +1 -1
  7. package/references/troubleshooting.md +1 -1
  8. package/scripts/bin/ledger-darwin-arm64 +0 -0
  9. package/scripts/bin/ledger-linux-amd64 +0 -0
  10. package/scripts/bin/ledger-windows-amd64.exe +0 -0
  11. package/scripts/progress +44 -0
  12. package/scripts/ledgerkit/__init__.py +0 -0
  13. package/scripts/ledgerkit/actions/__init__.py +0 -0
  14. package/scripts/ledgerkit/actions/atom.py +0 -154
  15. package/scripts/ledgerkit/actions/bootstrap.py +0 -37
  16. package/scripts/ledgerkit/actions/claim.py +0 -88
  17. package/scripts/ledgerkit/actions/close_task.py +0 -191
  18. package/scripts/ledgerkit/actions/guard.py +0 -158
  19. package/scripts/ledgerkit/actions/handoff.py +0 -93
  20. package/scripts/ledgerkit/actions/init_identity.py +0 -90
  21. package/scripts/ledgerkit/actions/list_tasks.py +0 -74
  22. package/scripts/ledgerkit/actions/log_progress.py +0 -67
  23. package/scripts/ledgerkit/actions/new_task.py +0 -129
  24. package/scripts/ledgerkit/actions/query.py +0 -35
  25. package/scripts/ledgerkit/actions/query_history.py +0 -220
  26. package/scripts/ledgerkit/actions/registry.py +0 -82
  27. package/scripts/ledgerkit/actions/relabel.py +0 -89
  28. package/scripts/ledgerkit/actions/release.py +0 -76
  29. package/scripts/ledgerkit/actions/result.py +0 -90
  30. package/scripts/ledgerkit/actions/set_task.py +0 -71
  31. package/scripts/ledgerkit/actions/show_task.py +0 -55
  32. package/scripts/ledgerkit/actions/validate.py +0 -189
  33. package/scripts/ledgerkit/core/__init__.py +0 -0
  34. package/scripts/ledgerkit/core/history_md.py +0 -152
  35. package/scripts/ledgerkit/core/identity.py +0 -54
  36. package/scripts/ledgerkit/core/ids.py +0 -58
  37. package/scripts/ledgerkit/core/labels.py +0 -89
  38. package/scripts/ledgerkit/core/paths.py +0 -92
  39. package/scripts/ledgerkit/core/roots.py +0 -74
  40. package/scripts/ledgerkit/core/time.py +0 -103
  41. package/scripts/ledgerkit/core/worklog_md.py +0 -435
  42. package/scripts/ledgerkit/env.py +0 -94
  43. package/scripts/ledgerkit/errors.py +0 -15
  44. package/scripts/ledgerkit/notices.py +0 -28
  45. package/scripts/ledgerkit/shell/__init__.py +0 -0
  46. package/scripts/ledgerkit/shell/cli.py +0 -532
  47. package/scripts/ledgerkit/shell/gitops.py +0 -668
  48. package/scripts/ledgerkit/shell/merge.py +0 -266
  49. package/scripts/ledgerkit/shell/presync.py +0 -23
  50. package/scripts/ledgerkit/shell/render.py +0 -216
  51. package/scripts/ledgerkit/shell/runner.py +0 -232
  52. package/scripts/ledgerkit/store/__init__.py +0 -0
  53. package/scripts/ledgerkit/store/atomic.py +0 -130
  54. package/scripts/ledgerkit/store/dirty.py +0 -108
  55. package/scripts/ledgerkit/store/history_store.py +0 -134
  56. package/scripts/ledgerkit/store/json_store.py +0 -166
  57. package/scripts/ledgerkit/store/locks.py +0 -64
  58. package/scripts/ledgerkit/store/owners_index.py +0 -127
  59. package/scripts/ledgerkit/store/task_store.py +0 -28
  60. package/scripts/ledgerkit/store/worklog_store.py +0 -178
  61. package/scripts/progress.py +0 -20
@@ -1,189 +0,0 @@
1
- """只读:台账体检。两档:默认浅度只查格式,`--deep` 才读全部历史。
2
-
3
- 浅度(默认):池 + 各分片的字段格式、索引与文件对不对得上、**当月**历史。
4
- 深度(`--deep`):历史不止当月(全部月份)。
5
-
6
- **两档都不读过程文档正文**(2026-10-27 用户拍板):过程文档是附件、存量可以上万篇,
7
- 逐篇读全文换不来体检结论,只白花时间;文档自身的格式与内容不在体检范围。
8
-
9
- 只查格式,不查业务(该谁结案、逾期与否都不管);也不查「同一任务号落在多个文件」——
10
- 读侧只显示一次(`list` / `show` 都不重复)、写侧已有防护,撞上了不关体检的事(2026-10-24 用户拍板)。
11
- """
12
-
13
- from __future__ import annotations
14
-
15
- from pathlib import Path
16
-
17
- from ..core import history_md
18
- from ..core.identity import Identity
19
- from ..core.labels import STATUSES
20
- from ..core.paths import (
21
- LEDGER_DIR,
22
- OWNERS_REL,
23
- POOL_REL,
24
- to_repo_rel,
25
- )
26
- from ..core.time import now
27
- from ..store.history_store import HistoryStore
28
- from ..store.owners_index import OwnersIndex
29
- from ..store.task_store import TaskStore
30
- from .guard import owner_of, status_of
31
- from .result import ValidationReport, rel
32
-
33
-
34
- def _read_tasks(repo: Path, store: TaskStore, problems: list[str]) -> dict:
35
- """读一个任务文件;撞上**程序自留**的冲突标记 ⇒ 记一条 problem 继续。
36
-
37
- 推送被拒后 rebase 给 JSON 留的 `<<<<<<<` 是程序自己产的坏数据,validate
38
- 要能指出来(退 1 给清单),而不是整条命令退 3(2026-10-24 修)。
39
- 其余读错误(用户手改坏)不在此列,照旧抛出。
40
- """
41
- try:
42
- return store.all()
43
- except ValueError:
44
- text = store.path.read_text(encoding="utf-8", errors="replace")
45
- if "<<<<<<<" in text:
46
- problems.append(
47
- f"{rel(repo, store.path)} 带着冲突标记"
48
- "(推送被拒后 rebase 没解完):先解决冲突,再跑 validate。"
49
- )
50
- return {}
51
- raise
52
-
53
-
54
- def _check_task_files(
55
- repo: Path, index: OwnersIndex, problems: list[str]
56
- ) -> tuple[int, int]:
57
- """池 + 各分片的字段格式(owner / status / 分片归属);返回 (查了几个文件, 几条任务)。"""
58
- checked = 0
59
- total = 0
60
-
61
- pool = TaskStore(repo, POOL_REL)
62
- if pool.path.exists():
63
- checked += 1
64
- for tid, task in _read_tasks(repo, pool, problems).items():
65
- total += 1
66
- if owner_of(task):
67
- problems.append(
68
- f"公共池里的 {tid} 带着 owner(池里的行必须无人认领)。"
69
- )
70
- if task.get("status") not in STATUSES:
71
- problems.append(f"公共池里的 {tid} 状态 {task.get('status')!r} 非法。")
72
-
73
- for key, path in index.shards().items():
74
- if not path.exists():
75
- problems.append(f"索引登记了 {key},但分片文件 {path.name} 不存在。")
76
- continue
77
- checked += 1
78
- store = TaskStore(repo, Path(path).relative_to(repo / "ledger"))
79
- for tid, task in _read_tasks(repo, store, problems).items():
80
- total += 1
81
- owner = owner_of(task)
82
- if not owner:
83
- problems.append(f"分片 {key} 里的 {tid} 没有 owner。")
84
- elif owner != key:
85
- problems.append(
86
- f"分片 {key} 里的 {tid} 的 owner 是 {owner}(分片主人与分区键不一致)。"
87
- )
88
- status = status_of(task)
89
- if status not in STATUSES:
90
- problems.append(f"分片 {key} 里的 {tid} 状态 {status!r} 非法。")
91
-
92
- return checked, total
93
-
94
-
95
- def _check_orphan_shards(index: OwnersIndex, problems: list[str]) -> None:
96
- """目录里有、索引没登记的分片(全仓唯一扫目录的地方)。"""
97
- registered = {p.name for p in index.shards().values()}
98
- for path in index.disk_shards():
99
- if path.name not in registered:
100
- problems.append(
101
- f"owners/ 里的 {path.name} 没有在索引里登记(对它人等于不存在)。"
102
- )
103
-
104
-
105
- def _history_paths(store: HistoryStore, *, deep: bool) -> list[Path]:
106
- """要读的历史文件:浅度只读当月那个月文件(存量平铺文件不读),深度读全部。"""
107
- sources = store.sources()
108
- if deep:
109
- return sources
110
- month = now()[0:4] + now()[5:7]
111
- return [p for p in sources if store.month_key(p) == month]
112
-
113
-
114
- def _check_history(
115
- repo: Path,
116
- paths: list[Path],
117
- open_docs: set[str],
118
- store: HistoryStore,
119
- notices: list[str],
120
- ) -> int:
121
- """历史文件的格式与对账:解析警告、行尾文档链接对得上在办任务没。"""
122
- checked = 0
123
- for path in paths:
124
- checked += 1
125
- rows, warns = history_md.parse_history(store.read(path))
126
- notices.extend(f"{rel(repo, path)}:{w}" for w in warns)
127
- for row in rows:
128
- name = Path(row.get("worklog") or "").name
129
- if name and name in open_docs:
130
- notices.append(
131
- f"历史里有「{row.get('title') or name}」的结案行,"
132
- "但它还挂在在办台账里。"
133
- )
134
- return checked
135
-
136
-
137
- def validate(repo: Path, me: Identity, deep: bool = False) -> ValidationReport:
138
- problems: list[str] = []
139
- notices: list[str] = []
140
- checked = 0
141
- total = 0
142
-
143
- index = OwnersIndex(repo)
144
- history = HistoryStore(repo)
145
-
146
- files, tasks = _check_task_files(repo, index, problems)
147
- checked += files
148
- total += tasks
149
- _check_orphan_shards(index, problems)
150
-
151
- checked += _check_history(
152
- repo,
153
- _history_paths(history, deep=deep),
154
- _open_worklog_names(repo, index),
155
- history,
156
- notices,
157
- )
158
-
159
- if not (repo / to_repo_rel(OWNERS_REL)).exists():
160
- notices.append("还没有 owners.json(索引):跑一条写命令会自动建。")
161
- stray = repo / LEDGER_DIR / LEDGER_DIR
162
- if stray.is_dir():
163
- problems.append(
164
- f"{rel(repo, stray)} 是错位的台账目录(根被当成 ledger/ 时写出来的幻影);"
165
- "确认哪份是真台账后删掉多余的,命令一律带 --repo <工作区根>。"
166
- )
167
-
168
- return ValidationReport(
169
- problems=tuple(problems),
170
- notices=tuple(notices),
171
- checked_files=checked,
172
- total_tasks=total,
173
- deep=deep,
174
- )
175
-
176
-
177
- def _open_worklog_names(repo: Path, index: OwnersIndex) -> set[str]:
178
- """在办任务的过程文档**文件名**集合(池 + 全部分片):历史行按它对账。"""
179
- stores = [TaskStore(repo, POOL_REL)]
180
- for path in index.shards().values():
181
- if path.exists():
182
- stores.append(TaskStore(repo, Path(path).relative_to(repo / "ledger")))
183
- out: set[str] = set()
184
- for store in stores:
185
- for task in store.all().values():
186
- name = Path((task.get("worklog") or "").strip()).name
187
- if name:
188
- out.add(name)
189
- return out
File without changes
@@ -1,152 +0,0 @@
1
- """历史表格的文本操作:拼十一列一行、解析十一列一行。
2
-
3
- **只认十一列这一种格式**:存量九列的文件按 `docs/history-creator-upgrade.md`
4
- 那份手册一次性升级,脚本不做运行时迁移。
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import re
10
- from collections.abc import Iterable
11
- from typing import Any
12
-
13
- from .paths import to_history_rel
14
- from .time import TIME_RE, time_key
15
-
16
- HISTORY_TITLE = "# 进度历史(已结案)"
17
- HISTORY_HEADER = (
18
- "| 结案时间 | 创建时间 | 标题 | 分类 | 标签 "
19
- "| owner | owner_name | creator | creator_name | 完成了什么 | 过程文档 |"
20
- )
21
- HISTORY_SEP = "|---|---|---|---|---|---|---|---|---|---|---|"
22
-
23
- _LINK_RE = re.compile(r"\[[^\]]*\]\(([^)]*)\)")
24
- _TAG_SPLIT_RE = re.compile(r"[,,、]")
25
-
26
- Row = dict[str, Any] # 一条历史行:见 parse_history 的返回
27
-
28
-
29
- def esc_cell(text: str) -> str:
30
- """表格单元格:折叠空白并转义竖线,避免把历史表格写坏。"""
31
- return " ".join((text or "").split()).replace("|", "\\|")
32
-
33
-
34
- def owner_cell(owner: str | None) -> str:
35
- """owner 列的值:裸 uuid,**不加 `@`**(`@` 只加在名字列;匹配一律用裸 uuid)。"""
36
- return owner or ""
37
-
38
-
39
- def creator_cell(creator: str | None) -> str:
40
- """creator 列的值(与 owner_cell 同一约定:裸 uuid,不加 `@`)。"""
41
- return creator or ""
42
-
43
-
44
- def name_cell(name: str | None) -> str:
45
- """名字列的展示值:名字前加 `@`(与过程文档 `@名字 · uuid` 同一口径)。"""
46
- return f"@{name}" if name else ""
47
-
48
-
49
- def split_row(line: str) -> list[str]:
50
- """按 `|` 切表格行:转义竖线 `\\|` 不当分隔符,切完反转义、去首尾空单元。"""
51
- cells = re.split(r"(?<!\\)\|", line.strip())
52
- if cells and cells[0] == "":
53
- cells = cells[1:]
54
- if cells and cells[-1] == "":
55
- cells = cells[:-1]
56
- return [c.strip().replace("\\|", "|") for c in cells]
57
-
58
-
59
- def is_sep_row(cells: list[str]) -> bool:
60
- return bool(cells) and all(re.fullmatch(r":?-+:?", c) for c in cells)
61
-
62
-
63
- def _looks_like_header(cells: list[str]) -> bool:
64
- return bool(cells) and cells[0] in ("时间", "结案时间")
65
-
66
-
67
- def history_line(
68
- finished: str,
69
- created: str | None,
70
- title: str,
71
- owner: str | None,
72
- summary: str,
73
- worklog: str | None,
74
- category: str | None = None,
75
- tags: Iterable[str] | None = None,
76
- creator: str | None = None,
77
- owner_name: str | None = None,
78
- creator_name: str | None = None,
79
- ) -> str:
80
- """十一列的一行。`worklog` 收**相对 `ledger/`** 的路径,这里负责换成相对 `history/` 的链接。
81
-
82
- owner / creator 传**裸 uuid**、名字传**裸名字**,两处都别先加 `@`:
83
- `@` 由 `name_cell` 只加在名字列(与过程文档 `@名字 · uuid` 同一口径),uuid 列永远是裸值。
84
- `owner_name` / `creator_name` 是**落盘的显示名快照**(结案那一刻的名字,之后改名不改旧行)。
85
- """
86
- log_rel = to_history_rel(worklog) if worklog else ""
87
- tag_cell = esc_cell("、".join(tags) if tags else "")
88
- link = f"[{log_rel}]({log_rel})" if log_rel else ""
89
- return (
90
- f"| {finished} | {created or ''} | {esc_cell(title)} "
91
- f"| {esc_cell(category or '')} | {tag_cell} "
92
- f"| {esc_cell(owner_cell(owner))} | {esc_cell(name_cell(owner_name))} "
93
- f"| {esc_cell(creator_cell(creator))} | {esc_cell(name_cell(creator_name))} "
94
- f"| {esc_cell(summary)} | {link} |\n"
95
- )
96
-
97
-
98
- def parse_history(text: str) -> tuple[list[Row], list[str]]:
99
- """解析十一列历史表 → (records, warnings)。坏行(列数不对 / 时间列不合法)跳过并警告。
100
-
101
- 返回的键:finished / created / title / category / tags / owner / owner_name /
102
- creator / creator_name / summary / worklog / fmt / line。owner 与 creator 两列
103
- **剥掉 `@`**(存储值是裸 uuid);两个名字列剥掉展示用的 `@`(落盘快照,可能为空)。
104
- """
105
- records: list[Row] = []
106
- warnings: list[str] = []
107
- for lineno, raw in enumerate(text.splitlines(), 1):
108
- if not raw.strip().startswith("|"):
109
- continue
110
- cells = split_row(raw)
111
- if not cells or is_sep_row(cells) or _looks_like_header(cells):
112
- continue
113
- if len(cells) != 11:
114
- warnings.append(f"第 {lineno} 行不是十一列(历史表只认十一列),已跳过")
115
- continue
116
- (
117
- finished,
118
- created,
119
- title,
120
- category,
121
- tag_cell,
122
- owner,
123
- owner_name,
124
- creator,
125
- creator_name,
126
- summary,
127
- doc,
128
- ) = cells
129
- if not TIME_RE.fullmatch(finished):
130
- warnings.append(f"第 {lineno} 行时间列 {finished!r} 不合法,已跳过")
131
- continue
132
- m = _LINK_RE.fullmatch(doc.strip())
133
- records.append(
134
- {
135
- "finished": finished,
136
- "created": time_key(created) if created else None,
137
- "title": title,
138
- "category": category.strip() or None,
139
- "tags": tuple(
140
- t.strip() for t in _TAG_SPLIT_RE.split(tag_cell) if t.strip()
141
- ),
142
- "owner": owner.strip().removeprefix("@") or None,
143
- "owner_name": owner_name.strip().removeprefix("@") or None,
144
- "creator": creator.strip().removeprefix("@") or None,
145
- "creator_name": creator_name.strip().removeprefix("@") or None,
146
- "summary": summary,
147
- "worklog": (m.group(1) if m else doc.strip()) or None,
148
- "fmt": "v11",
149
- "line": lineno,
150
- }
151
- )
152
- return records, warnings
@@ -1,54 +0,0 @@
1
- """身份这个值对象:uuid 是唯一键,name 只用于显示与查询筛选。
2
-
3
- **只做字符串换算,不读文件**(读身份归 env.py)。名字永远不参与归属判定:
4
- 认领 / 释放 / 交接 / 查「我的」,一律只比 uuid。
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import re
10
- from dataclasses import dataclass
11
-
12
- #: 合法身份键的形态(8-4-4-4-12 的十六进制 UUID)。`--owner` 只收这种值。
13
- UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
14
-
15
-
16
- @dataclass(frozen=True)
17
- class Identity:
18
- """一个人的身份。`uuid` 是唯一键,`name` 只用于显示。"""
19
-
20
- uuid: str
21
- name: str = ""
22
-
23
- def label(self) -> str:
24
- """显示名:没名字就用 uuid 前 8 位。只给人看(报错文案、界面)。"""
25
- return self.name or self.uuid[:8]
26
-
27
- def stamp(self) -> str:
28
- """**落盘**用的身份串:`名字 · uuid` —— 名字在前给人读,uuid 在后给机器对。
29
-
30
- 与 `label()` 一样**不带 `@`**(`@` 由各落点自己加:头部各行拼 ` · @{stamp}`、
31
- `exec_line` 拼 ` · @{who} · `)。
32
-
33
- 过程文档(创建行 / 状态行 / 封卷行 / 执行记录)是这个串唯一的落点:文件是最终产物,
34
- 创建人和封卷人可能不是同一个人、也可能中途改过名,所以**两个都要留**,不靠
35
- 历史表回链。没名字就只写 uuid。
36
- """
37
- if not self.name:
38
- return self.uuid
39
- return f"{self.name} · {self.uuid}"
40
-
41
-
42
- def normalize(who: str) -> str:
43
- """归一化:去首尾空白 + 转小写。全仓只此一处。"""
44
- return (who or "").strip().lower()
45
-
46
-
47
- def looks_like_uuid(who: str | None) -> bool:
48
- """是不是一个 UUID 形态的身份键(名字、邮箱一律 False)。"""
49
- return bool(UUID_RE.match(normalize(who or "")))
50
-
51
-
52
- def is_me(identity: Identity, who: str | None) -> bool:
53
- """`who`(uuid)是不是这个人。全站只认 uuid 这一个身份键。"""
54
- return normalize(who or "") == normalize(identity.uuid)
@@ -1,58 +0,0 @@
1
- """任务号:生成、形态校验。只做字符串换算。"""
2
-
3
- from __future__ import annotations
4
-
5
- import re
6
- import secrets
7
- from collections.abc import Mapping
8
-
9
- from ..errors import Fail
10
- from .time import now
11
-
12
- ID_RE = re.compile(r"[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]*\Z")
13
-
14
-
15
- def slugify(title: str) -> str:
16
- """任务号用:保留 ASCII 字母数字与汉字,其余转连字符,截到 40 字。"""
17
- s = re.sub(r"[^a-z0-9\u4e00-\u9fff]+", "-", title.strip().lower())
18
- return s.strip("-")[:40].strip("-")
19
-
20
-
21
- def id_stamp(created: str) -> str:
22
- """`created`(YYYY-MM-DD HH:MM:SS)→ 任务号前缀 `YYYYMMDD-HHMM`(任务号只到分)。"""
23
- return (
24
- f"{created[0:4]}{created[5:7]}{created[8:10]}-{created[11:13]}{created[14:16]}"
25
- )
26
-
27
-
28
- def make_id(title: str, tasks: Mapping[str, object], created: str | None = None) -> str:
29
- """按标题生成一个不撞号的任务号。
30
-
31
- 随机码不能省:`make_id` 只在**在办**任务里去重,而结案的过程文档长期留在磁盘上,
32
- 去掉随机码会让新任务撞上已结案文档的名字。
33
- """
34
- slug = slugify(title)
35
- if not slug:
36
- raise Fail(
37
- "标题里没有可用字符(字母、数字或汉字),无法自动生成任务号。"
38
- f'用 --id 指定一个,例如 --id "task-{secrets.token_hex(2)}"。'
39
- )
40
- stamp = id_stamp(created or now())
41
- for _ in range(20):
42
- tid = f"{stamp}-{slug}-{secrets.token_hex(2)}"
43
- if tid not in tasks:
44
- return tid
45
- raise Fail("任务号连续冲突 20 次,请检查台账是否异常。")
46
-
47
-
48
- def require_task_id(tid: str) -> str:
49
- """任务号形态校验(全仓唯一入口)。不合法直接抛 Fail。"""
50
- value = (tid or "").strip()
51
- if not value:
52
- raise Fail("任务号不能为空。")
53
- if not ID_RE.fullmatch(value.lower()):
54
- raise Fail(
55
- f"任务号 {tid!r} 不合法:只能用小写字母、数字、汉字和连字符,"
56
- "且不能以连字符开头或结尾。"
57
- )
58
- return value
@@ -1,89 +0,0 @@
1
- """分类与标签:校验、拼行、拆行。只做文本换算。"""
2
-
3
- from __future__ import annotations
4
-
5
- import re
6
- from collections.abc import Iterable
7
-
8
- from ..errors import Fail
9
-
10
- STATUSES = ("open", "doing")
11
- FORMAT_VERSION = "20261022000000"
12
-
13
- LABEL_MAX_CHARS = 4 # 含 CJK 时按「字」算
14
- LABEL_MAX_WORDS_EN = 3 # 纯 ASCII 时按「词」算
15
- TAGS_MAX_COUNT = 5
16
-
17
- CJK_RE = re.compile(r"[\u4e00-\u9fff]")
18
- LABEL_CAT_RE = re.compile(r"分类\*\*\s*[::]\s*([^||·]+)")
19
- LABEL_TAG_RE = re.compile(r"标签\*\*\s*[::]\s*(.+)$")
20
- _SPLIT_RE = re.compile(r"[,,、]")
21
-
22
-
23
- def normalize_label(value: str, *, field: str) -> str:
24
- """分类 / 单个标签的校验:去空白、限长。空串直接 Fail(给了就要有意义)。"""
25
- text = (value or "").strip()
26
- if not text:
27
- raise Fail(f"{field} 不能为空。")
28
- if CJK_RE.search(text):
29
- if len(text) > LABEL_MAX_CHARS:
30
- raise Fail(f"{field} {text!r} 太长:含中文时最多 {LABEL_MAX_CHARS} 个字。")
31
- elif len(text.split()) > LABEL_MAX_WORDS_EN:
32
- raise Fail(f"{field} {text!r} 太长:英文最多 {LABEL_MAX_WORDS_EN} 个词。")
33
- return text
34
-
35
-
36
- def parse_tags(raw: str | Iterable[str] | None) -> tuple[str, ...]:
37
- """标签串(「、」「,」「,」分隔)→ 去重保序的元组;超上限报错。"""
38
- if raw is None:
39
- return ()
40
- items = list(raw) if not isinstance(raw, str) else _SPLIT_RE.split(raw)
41
- out: list[str] = []
42
- for item in items:
43
- text = normalize_label(str(item).strip(), field="标签")
44
- if text not in out:
45
- out.append(text)
46
- if len(out) > TAGS_MAX_COUNT:
47
- raise Fail(f"标签最多 {TAGS_MAX_COUNT} 个,收到 {len(out)} 个。")
48
- return tuple(out)
49
-
50
-
51
- def label_line(tags: Iterable[str] | None) -> str:
52
- """过程文档头部的「标签」行;标签为空返回空串(此行不写)。
53
-
54
- 分类**不进过程文档**(2026-10-27 用户拍板):它只活在分片字段与历史表里,
55
- 标签可涵盖分类(「建设」「修改」这类词直接当标签写)。
56
- """
57
- tag_list = [t for t in (tags or ()) if t]
58
- return f"- **标签**:{'、'.join(tag_list)}" if tag_list else ""
59
-
60
-
61
- def parse_label_line(text: str) -> tuple[str | None, tuple[str, ...]]:
62
- """从过程文档头部(第一个 `## ` 小节之前)解析分类与标签。
63
-
64
- 跳过 HTML 注释块:模板注释里的示例不是数据。老文档的分类段照样能解析出来。
65
- """
66
- in_comment = False
67
- for line in text.splitlines():
68
- if line.startswith("## "):
69
- break
70
- stripped = line.lstrip()
71
- if in_comment:
72
- if "-->" in stripped:
73
- in_comment = False
74
- continue
75
- if stripped.startswith("<!--"):
76
- in_comment = "-->" not in stripped
77
- continue
78
- mc = LABEL_CAT_RE.search(line)
79
- mt = LABEL_TAG_RE.search(line)
80
- if not (mc or mt):
81
- continue
82
- category = mc.group(1).strip() if mc else None
83
- tags = (
84
- tuple(t.strip() for t in _SPLIT_RE.split(mt.group(1).strip()) if t.strip())
85
- if mt
86
- else ()
87
- )
88
- return (category or None, tags)
89
- return (None, ())
@@ -1,92 +0,0 @@
1
- """路径与文件名怎么拼:只做换算,一个文件都不碰。
2
-
3
- **基准只有两个**:
4
- - 磁盘与 JSON 里存的(`task["worklog"]` 等)一律**相对 `ledger/`**;
5
- - 输出给人或给界面的(`Result.where`、`payload` 里的 `*_path`)一律**相对 repo**。
6
-
7
- 换算只在这两个函数里做,任何层都不许自己拼 `..`。
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import hashlib
13
- import re
14
- from pathlib import Path
15
-
16
- LEDGER_DIR = Path("ledger")
17
-
18
- POOL_REL = Path("pool.json")
19
- OWNERS_REL = Path("owners.json")
20
- OWNERS_DIR = Path("owners")
21
- HISTORY_DIR = Path("history")
22
- WORKLOG_DIR = Path("worklog")
23
-
24
- SHA_LEN = 12
25
-
26
- # 模板与资产的唯一定位基准:按自身位置算绝对路径,不依赖调用方 cwd。
27
- # ledgerkit/core/paths.py → parents: [core, ledgerkit, scripts, skill]
28
- SKILL_DIR = Path(__file__).resolve().parents[3]
29
- WORKLOG_TEMPLATE = SKILL_DIR / "assets" / "worklog.md"
30
-
31
-
32
- def to_repo_rel(ledger_rel: str | Path) -> Path:
33
- """相对 `ledger/` 的路径 → 相对 repo 的路径。"""
34
- return LEDGER_DIR / Path(ledger_rel)
35
-
36
-
37
- def to_ledger_rel(repo_rel: str | Path) -> str:
38
- """相对 repo 的路径 → 相对 `ledger/` 的路径(已经是 `ledger/` 内的原样返回)。"""
39
- p = Path(repo_rel)
40
- if p.parts and p.parts[0] == LEDGER_DIR.name:
41
- return Path(*p.parts[1:]).as_posix()
42
- return p.as_posix()
43
-
44
-
45
- def to_history_rel(ledger_rel: str | Path) -> str:
46
- """`ledger/` 内的路径 → 从 `ledger/history/<ym>.md` 出发的链接串。
47
-
48
- 深度固定(`history/` 与 `worklog/` 都在 `ledger/` 下),拼 `..` 只许在这一处。
49
- """
50
- return ("../" / Path(ledger_rel)).as_posix()
51
-
52
-
53
- def shard_rel(identity: str) -> Path:
54
- """某人分片相对 `ledger/` 的路径:sha256(归一化身份)[:12] + .json。"""
55
- digest = hashlib.sha256(identity.strip().lower().encode("utf-8")).hexdigest()
56
- return OWNERS_DIR / f"{digest[:SHA_LEN]}.json"
57
-
58
-
59
- def month_of(stamp: str, *, fallback_now: str | None = None) -> str:
60
- """存盘时间 → `YYYYMM`;取不到时用 `fallback_now`,再没有就抛错由调用方定夺。"""
61
- month = re.sub(r"[^0-9]", "", (stamp or "")[:7])[:6]
62
- if len(month) == 6:
63
- return month
64
- if fallback_now:
65
- return re.sub(r"[^0-9]", "", fallback_now[:7])[:6]
66
- return ""
67
-
68
-
69
- def worklog_dir_for(created: str) -> Path:
70
- """过程文档的按月目录(相对 `ledger/`):`worklog/<YYYYMM>/`。"""
71
- return WORKLOG_DIR / month_of(created)
72
-
73
-
74
- def worklog_name(tid: str) -> str:
75
- """过程文档的文件名:任务号剥掉前缀年月日,随机码保留。
76
-
77
- 父目录 `worklog/<YYYYMM>/` 已带年月,文件名里再写一遍是冗余;
78
- 自定义 `--id` 不以「8 位数字-」开头时,文件名就是任务号本身。
79
- """
80
- if len(tid) > 9 and tid[:8].isdigit() and tid[8] == "-":
81
- return f"{tid[6:]}.md"
82
- return f"{tid}.md"
83
-
84
-
85
- def worklog_rel(tid: str, created: str) -> str:
86
- """过程文档相对 `ledger/` 的路径:任务对象与历史末列共用同一口径。"""
87
- return (worklog_dir_for(created) / worklog_name(tid)).as_posix()
88
-
89
-
90
- def history_path_for(finished: str) -> Path:
91
- """结案时间 → 历史文件相对 `ledger/` 的路径:`history/<YYYYMM>.md`。"""
92
- return HISTORY_DIR / f"{month_of(finished)}.md"