codebee 0.1.76 → 0.1.78

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 (115) hide show
  1. package/CHANGELOG.md +633 -624
  2. package/LICENSE +21 -21
  3. package/README.md +508 -509
  4. package/app/.playwright-cli/console-2026-09-23T08-26-03-635Z.log +88 -0
  5. package/app/.playwright-cli/page-2026-09-23T08-26-03-845Z.yml +126 -0
  6. package/app/.playwright-cli/page-2026-09-23T08-29-44-203Z.png +0 -0
  7. package/app/.playwright-cli/page-2026-09-23T08-35-42-046Z.yml +210 -0
  8. package/app/.playwright-cli/page-2026-09-23T08-36-52-858Z.png +0 -0
  9. package/app/.playwright-cli/page-2026-09-23T08-37-33-938Z.png +0 -0
  10. package/app/.playwright-cli/run-detail-after.png +0 -0
  11. package/app/core/acceptance.py +100 -100
  12. package/app/core/aiflavor.py +197 -197
  13. package/app/core/analytics.py +38 -38
  14. package/app/core/artifacts.py +148 -148
  15. package/app/core/assets.py +110 -110
  16. package/app/core/attachments.py +623 -623
  17. package/app/core/audit.py +30 -30
  18. package/app/core/backup.py +470 -470
  19. package/app/core/beekeeper.py +183 -183
  20. package/app/core/benchstore.py +95 -95
  21. package/app/core/board.py +209 -209
  22. package/app/core/bookmeta.py +1036 -1036
  23. package/app/core/bookmeta_catalog.py +180 -180
  24. package/app/core/branching.py +137 -137
  25. package/app/core/builtin_agent.py +1680 -1680
  26. package/app/core/capability.py +144 -144
  27. package/app/core/chaptersafe.py +32 -32
  28. package/app/core/cleanup.py +303 -303
  29. package/app/core/compaction.py +201 -201
  30. package/app/core/contracts.py +255 -255
  31. package/app/core/covergen.py +356 -356
  32. package/app/core/defectretro.py +43 -43
  33. package/app/core/diagnostics.py +114 -114
  34. package/app/core/dispatch.py +190 -190
  35. package/app/core/dispatch_log.py +128 -128
  36. package/app/core/env_scrub.py +85 -85
  37. package/app/core/errorlog.py +137 -137
  38. package/app/core/evaluation.py +174 -174
  39. package/app/core/failure_notify.py +290 -290
  40. package/app/core/goal_service.py +167 -167
  41. package/app/core/health.py +389 -389
  42. package/app/core/history.py +38 -38
  43. package/app/core/hooks.py +162 -162
  44. package/app/core/manager.py +2232 -2232
  45. package/app/core/mocks.py +64 -64
  46. package/app/core/notify.py +201 -201
  47. package/app/core/novel_quality.py +189 -189
  48. package/app/core/openapi.py +154 -154
  49. package/app/core/operations.py +228 -228
  50. package/app/core/paihang.py +145 -145
  51. package/app/core/pipeline.py +29 -0
  52. package/app/core/planner.py +88 -0
  53. package/app/core/portguard.py +111 -111
  54. package/app/core/presence.py +77 -77
  55. package/app/core/preview.py +293 -293
  56. package/app/core/prompt_guard.py +78 -78
  57. package/app/core/publish/__init__.py +7 -7
  58. package/app/core/publish/browser.py +655 -655
  59. package/app/core/publish/fanqie.py +165 -165
  60. package/app/core/publish/flow.py +640 -640
  61. package/app/core/publish/flows-fanqie-calibrated.json +336 -336
  62. package/app/core/publish/manager.py +1118 -1118
  63. package/app/core/publish/qimao.py +176 -176
  64. package/app/core/publish/ws.py +139 -139
  65. package/app/core/quality_gate.py +194 -194
  66. package/app/core/redact.py +38 -38
  67. package/app/core/repeat_guard.py +129 -129
  68. package/app/core/retrieval.py +137 -137
  69. package/app/core/router.py +398 -398
  70. package/app/core/runner.py +2238 -2238
  71. package/app/core/selfupdate.py +384 -384
  72. package/app/core/session_log.py +161 -161
  73. package/app/core/sessions.py +312 -312
  74. package/app/core/settings_schema.py +270 -270
  75. package/app/core/share_page.py +114 -114
  76. package/app/core/skill_scan.py +139 -139
  77. package/app/core/skillpacks/market/character-bible.md +66 -66
  78. package/app/core/skillpacks/market/code-risk-checklist.md +58 -58
  79. package/app/core/skillpacks/market/git-workflow.md +57 -57
  80. package/app/core/skillpacks/market/release-notes.md +72 -72
  81. package/app/core/skillpacks/market/weekly-report.md +71 -71
  82. package/app/core/skillpacks/market/worldview-consistency.md +70 -70
  83. package/app/core/skills.py +1 -1
  84. package/app/core/step_runner.py +132 -132
  85. package/app/core/story_tracking.py +275 -275
  86. package/app/core/task_compile.py +199 -199
  87. package/app/core/telemetry.py +292 -292
  88. package/app/core/tlsctx.py +64 -64
  89. package/app/core/token_meter.py +147 -147
  90. package/app/core/tracing.py +144 -144
  91. package/app/core/upstream.py +41 -41
  92. package/app/core/usage.py +1035 -1035
  93. package/app/core/volumes.py +389 -389
  94. package/app/core/wxdigest.py +858 -858
  95. package/app/core/zentao.py +2692 -2692
  96. package/app/mcp_server.py +244 -244
  97. package/app/output/_createbook_body.json +1 -0
  98. package/app/output/_probe_fq_click.py +50 -0
  99. package/app/output/_probe_fq_form.py +42 -0
  100. package/app/output/_probe_fq_modal.py +55 -0
  101. package/app/output/_probe_fq_points.py +71 -0
  102. package/app/output/_probe_fq_submit.py +34 -0
  103. package/app/output/_probe_fq_watch.py +62 -0
  104. package/app/pick_dialog.py +110 -110
  105. package/app/ui/artdiff.js +74 -74
  106. package/app/ui/board.html +162 -162
  107. package/app/ui/board.js +305 -305
  108. package/app/ui/i18n.js +2 -2
  109. package/app/ui/icons/bee.svg +79 -79
  110. package/app/ui/manifest.json +16 -16
  111. package/app/ui/qrcode.js +2297 -2297
  112. package/app/ui/style.css +7086 -7086
  113. package/bin/tutti.js +147 -147
  114. package/package.json +48 -48
  115. package/tools/wx_reader.py +261 -261
@@ -1,148 +1,148 @@
1
- """工作目录成品扫描:剪枝遍历 + 短 TTL 缓存 + 在飞合并。
2
-
3
- 历史实现用 Path.rglob("*") 全量展开再逐文件 is_file()/stat() 过滤,几万文件的
4
- 工作目录单次要 1.6~4 秒;而详情页/侧栏在任务运行中是轮询调用——每次轮询都是
5
- 一次全仓扫描,UI 整体被拖卡(2026-09-24 详情页卡顿案)。这里改为 os.walk
6
- 剪枝(跳过类目录整个不进入),并给重复轮询加 (workdir, t0, 任务状态) 键的短 TTL 缓存
7
- 与在飞合并:并发同键只扫一次,后到者等结果。
8
- """
9
- from __future__ import annotations
10
-
11
- import os
12
- import threading
13
- import time
14
-
15
- # 过滤语义与历史 rglob 版逐条对齐:
16
- # - SKIP_DIRS:任意路径段(含文件名本身)命中即剔除;
17
- # - BUILD_DIRS:仅祖先目录命中即剔除(文件名叫 dist 不受影响);
18
- # - 点开头:仅祖先目录算「隐藏」(根下的 .gitignore 这类隐藏文件仍是候选)。
19
- SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".idea", ".vscode"}
20
-
21
- # 构建产物/依赖缓存目录:里面的文件是工具链再生成的,不是任务成品
22
- BUILD_DIRS = {
23
- "target", "build", "dist", "out", "bin", "obj", # 通用构建输出
24
- "surefire", "failsafe-reports", "test-output", "reports", # 测试/报告输出
25
- ".next", ".nuxt", ".output", ".gradle", ".gradle-home", # 前端/Gradle
26
- "__MACOSX",
27
- }
28
-
29
- # CLI 自身的历史/评审中间件不属于用户成果。它们通常落在工作目录根部,
30
- # 只按隐藏目录过滤会漏掉 Aider 的 .aider.* 与流程生成的 *_review.json。
31
- _PROCESS_ARTIFACT_NAMES = {
32
- ".aider.chat.history.md", ".aider.input.history", ".aider.input.history.md",
33
- ".aider.tags.cache.v4", ".aider.tags.cache.v3", ".aider.conf.yml",
34
- }
35
- _PROCESS_ARTIFACT_SUFFIXES = ("_review.json", ".review.json")
36
- _PROCESS_ARTIFACT_PREFIXES = ("tutti_prompt_", "_tutti_prompt_")
37
-
38
- SCAN_CAP = 800 # 防超大目录拖垮接口;截断后再排序取最新
39
- CACHE_TTL_RUNNING = 2.0 # 任务在跑:轮询热,新鲜期要短
40
- CACHE_TTL_IDLE = 10.0 # 终态任务:详情反复开关/检查器同刷,可稍长
41
- _CACHE_KEEP = 128 # 缓存条目上限(按时间淘汰最旧)
42
-
43
- _now = time.monotonic # 模块级别名,测试可替换时钟
44
-
45
- _LOCK = threading.Lock()
46
- _CACHE = {} # (root, t0, running) -> (时间戳, files);files 恒为全量候选
47
- _INFLIGHT = {} # (root, t0, running) -> Lock;同键并发只跑一次扫描
48
-
49
-
50
- def _is_process_artifact(rel_name):
51
- """判断工作目录文件是否为 CLI/评审过程产物,而非可交付成果。"""
52
- name = str(rel_name or "").replace("\\", "/")
53
- base = name.rsplit("/", 1)[-1].lower()
54
- if base in _PROCESS_ARTIFACT_NAMES:
55
- return True
56
- if base.startswith(".") and base.startswith(".aider"):
57
- return True
58
- if base.endswith(_PROCESS_ARTIFACT_SUFFIXES):
59
- return True
60
- if base.startswith(_PROCESS_ARTIFACT_PREFIXES):
61
- return True
62
- return False
63
-
64
-
65
- def _walk_files(root, t0):
66
- """剪枝遍历:跳过类目录整个不进入;返回 mtime>=t0 的候选(无序)。"""
67
- files = []
68
- for dp, dirnames, filenames in os.walk(root):
69
- dirnames[:] = [d for d in dirnames
70
- if d not in SKIP_DIRS and d not in BUILD_DIRS
71
- and not d.startswith(".")]
72
- done = False
73
- for name in filenames:
74
- if name in SKIP_DIRS: # 历史语义:文件名本身命中也剔除
75
- continue
76
- try:
77
- st = os.stat(os.path.join(dp, name))
78
- except OSError:
79
- continue
80
- if st.st_mtime < t0:
81
- continue
82
- rel_dir = os.path.relpath(dp, root)
83
- rel = name if rel_dir == "." else \
84
- rel_dir.replace("\\", "/") + "/" + name
85
- if _is_process_artifact(rel):
86
- continue
87
- files.append({"name": rel,
88
- "size": st.st_size, "mtime": int(st.st_mtime)})
89
- if len(files) >= SCAN_CAP:
90
- done = True
91
- break
92
- if done:
93
- break
94
- return files
95
-
96
-
97
- def _cache_get(key, ttl):
98
- with _LOCK:
99
- ent = _CACHE.get(key)
100
- if ent and _now() - ent[0] < ttl:
101
- return ent[1]
102
- return None
103
-
104
-
105
- def _cache_put(key, files):
106
- with _LOCK:
107
- _CACHE[key] = (_now(), files)
108
- while len(_CACHE) > _CACHE_KEEP:
109
- _CACHE.pop(min(_CACHE, key=lambda k: _CACHE[k][0]), None)
110
-
111
-
112
- def _inflight_lock(key):
113
- with _LOCK:
114
- lock = _INFLIGHT.get(key)
115
- if lock is None:
116
- lock = _INFLIGHT[key] = threading.Lock()
117
- return lock
118
-
119
-
120
- def scan(root, t0, limit=200, running=False, cache=False):
121
- """扫工作目录成品,按 mtime 新→旧取前 limit 条,返回文件字典列表。
122
-
123
- cache=True 时同键 (root, t0, running) 在 TTL 内直接复用上次结果,运行中
124
- 任务用短 TTL;无论是否缓存,同键在飞扫描都会合并——轮询方只会等一次扫描。
125
- """
126
- # 运行态和终态必须分开缓存:任务刚结束时不能沿用运行中缓存里的旧
127
- # 文件列表,否则终态较长 TTL 会把最后写入的产物遮住。
128
- key = (str(root), t0, bool(running))
129
- ttl = CACHE_TTL_RUNNING if running else CACHE_TTL_IDLE
130
- if cache:
131
- hit = _cache_get(key, ttl)
132
- if hit is not None:
133
- return hit[:limit]
134
- klock = _inflight_lock(key)
135
- try:
136
- with klock:
137
- if cache: # 排到锁时他人可能已扫完入缓存
138
- hit = _cache_get(key, ttl)
139
- if hit is not None:
140
- return hit[:limit]
141
- files = sorted(_walk_files(root, t0), key=lambda f: -f["mtime"])
142
- if cache:
143
- _cache_put(key, files)
144
- finally:
145
- with _LOCK:
146
- if _INFLIGHT.get(key) is klock:
147
- _INFLIGHT.pop(key, None)
148
- return files[:limit]
1
+ """工作目录成品扫描:剪枝遍历 + 短 TTL 缓存 + 在飞合并。
2
+
3
+ 历史实现用 Path.rglob("*") 全量展开再逐文件 is_file()/stat() 过滤,几万文件的
4
+ 工作目录单次要 1.6~4 秒;而详情页/侧栏在任务运行中是轮询调用——每次轮询都是
5
+ 一次全仓扫描,UI 整体被拖卡(2026-09-24 详情页卡顿案)。这里改为 os.walk
6
+ 剪枝(跳过类目录整个不进入),并给重复轮询加 (workdir, t0, 任务状态) 键的短 TTL 缓存
7
+ 与在飞合并:并发同键只扫一次,后到者等结果。
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import threading
13
+ import time
14
+
15
+ # 过滤语义与历史 rglob 版逐条对齐:
16
+ # - SKIP_DIRS:任意路径段(含文件名本身)命中即剔除;
17
+ # - BUILD_DIRS:仅祖先目录命中即剔除(文件名叫 dist 不受影响);
18
+ # - 点开头:仅祖先目录算「隐藏」(根下的 .gitignore 这类隐藏文件仍是候选)。
19
+ SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".idea", ".vscode"}
20
+
21
+ # 构建产物/依赖缓存目录:里面的文件是工具链再生成的,不是任务成品
22
+ BUILD_DIRS = {
23
+ "target", "build", "dist", "out", "bin", "obj", # 通用构建输出
24
+ "surefire", "failsafe-reports", "test-output", "reports", # 测试/报告输出
25
+ ".next", ".nuxt", ".output", ".gradle", ".gradle-home", # 前端/Gradle
26
+ "__MACOSX",
27
+ }
28
+
29
+ # CLI 自身的历史/评审中间件不属于用户成果。它们通常落在工作目录根部,
30
+ # 只按隐藏目录过滤会漏掉 Aider 的 .aider.* 与流程生成的 *_review.json。
31
+ _PROCESS_ARTIFACT_NAMES = {
32
+ ".aider.chat.history.md", ".aider.input.history", ".aider.input.history.md",
33
+ ".aider.tags.cache.v4", ".aider.tags.cache.v3", ".aider.conf.yml",
34
+ }
35
+ _PROCESS_ARTIFACT_SUFFIXES = ("_review.json", ".review.json")
36
+ _PROCESS_ARTIFACT_PREFIXES = ("tutti_prompt_", "_tutti_prompt_")
37
+
38
+ SCAN_CAP = 800 # 防超大目录拖垮接口;截断后再排序取最新
39
+ CACHE_TTL_RUNNING = 2.0 # 任务在跑:轮询热,新鲜期要短
40
+ CACHE_TTL_IDLE = 10.0 # 终态任务:详情反复开关/检查器同刷,可稍长
41
+ _CACHE_KEEP = 128 # 缓存条目上限(按时间淘汰最旧)
42
+
43
+ _now = time.monotonic # 模块级别名,测试可替换时钟
44
+
45
+ _LOCK = threading.Lock()
46
+ _CACHE = {} # (root, t0, running) -> (时间戳, files);files 恒为全量候选
47
+ _INFLIGHT = {} # (root, t0, running) -> Lock;同键并发只跑一次扫描
48
+
49
+
50
+ def _is_process_artifact(rel_name):
51
+ """判断工作目录文件是否为 CLI/评审过程产物,而非可交付成果。"""
52
+ name = str(rel_name or "").replace("\\", "/")
53
+ base = name.rsplit("/", 1)[-1].lower()
54
+ if base in _PROCESS_ARTIFACT_NAMES:
55
+ return True
56
+ if base.startswith(".") and base.startswith(".aider"):
57
+ return True
58
+ if base.endswith(_PROCESS_ARTIFACT_SUFFIXES):
59
+ return True
60
+ if base.startswith(_PROCESS_ARTIFACT_PREFIXES):
61
+ return True
62
+ return False
63
+
64
+
65
+ def _walk_files(root, t0):
66
+ """剪枝遍历:跳过类目录整个不进入;返回 mtime>=t0 的候选(无序)。"""
67
+ files = []
68
+ for dp, dirnames, filenames in os.walk(root):
69
+ dirnames[:] = [d for d in dirnames
70
+ if d not in SKIP_DIRS and d not in BUILD_DIRS
71
+ and not d.startswith(".")]
72
+ done = False
73
+ for name in filenames:
74
+ if name in SKIP_DIRS: # 历史语义:文件名本身命中也剔除
75
+ continue
76
+ try:
77
+ st = os.stat(os.path.join(dp, name))
78
+ except OSError:
79
+ continue
80
+ if st.st_mtime < t0:
81
+ continue
82
+ rel_dir = os.path.relpath(dp, root)
83
+ rel = name if rel_dir == "." else \
84
+ rel_dir.replace("\\", "/") + "/" + name
85
+ if _is_process_artifact(rel):
86
+ continue
87
+ files.append({"name": rel,
88
+ "size": st.st_size, "mtime": int(st.st_mtime)})
89
+ if len(files) >= SCAN_CAP:
90
+ done = True
91
+ break
92
+ if done:
93
+ break
94
+ return files
95
+
96
+
97
+ def _cache_get(key, ttl):
98
+ with _LOCK:
99
+ ent = _CACHE.get(key)
100
+ if ent and _now() - ent[0] < ttl:
101
+ return ent[1]
102
+ return None
103
+
104
+
105
+ def _cache_put(key, files):
106
+ with _LOCK:
107
+ _CACHE[key] = (_now(), files)
108
+ while len(_CACHE) > _CACHE_KEEP:
109
+ _CACHE.pop(min(_CACHE, key=lambda k: _CACHE[k][0]), None)
110
+
111
+
112
+ def _inflight_lock(key):
113
+ with _LOCK:
114
+ lock = _INFLIGHT.get(key)
115
+ if lock is None:
116
+ lock = _INFLIGHT[key] = threading.Lock()
117
+ return lock
118
+
119
+
120
+ def scan(root, t0, limit=200, running=False, cache=False):
121
+ """扫工作目录成品,按 mtime 新→旧取前 limit 条,返回文件字典列表。
122
+
123
+ cache=True 时同键 (root, t0, running) 在 TTL 内直接复用上次结果,运行中
124
+ 任务用短 TTL;无论是否缓存,同键在飞扫描都会合并——轮询方只会等一次扫描。
125
+ """
126
+ # 运行态和终态必须分开缓存:任务刚结束时不能沿用运行中缓存里的旧
127
+ # 文件列表,否则终态较长 TTL 会把最后写入的产物遮住。
128
+ key = (str(root), t0, bool(running))
129
+ ttl = CACHE_TTL_RUNNING if running else CACHE_TTL_IDLE
130
+ if cache:
131
+ hit = _cache_get(key, ttl)
132
+ if hit is not None:
133
+ return hit[:limit]
134
+ klock = _inflight_lock(key)
135
+ try:
136
+ with klock:
137
+ if cache: # 排到锁时他人可能已扫完入缓存
138
+ hit = _cache_get(key, ttl)
139
+ if hit is not None:
140
+ return hit[:limit]
141
+ files = sorted(_walk_files(root, t0), key=lambda f: -f["mtime"])
142
+ if cache:
143
+ _cache_put(key, files)
144
+ finally:
145
+ with _LOCK:
146
+ if _INFLIGHT.get(key) is klock:
147
+ _INFLIGHT.pop(key, None)
148
+ return files[:limit]
@@ -1,110 +1,110 @@
1
- # -*- coding: utf-8 -*-
2
- """Content-addressed asset index.
3
-
4
- The index owns references and revisions, not file contents. Files stay in the
5
- task workspace; projects/runs can safely point to ``asset_id + revision_id``
6
- without making a second copy of a document.
7
- """
8
- from __future__ import annotations
9
-
10
- import json
11
- import hashlib
12
- import mimetypes
13
- import threading
14
- import time
15
- from pathlib import Path
16
-
17
- from . import paths
18
-
19
- LOCK = threading.RLock()
20
-
21
-
22
- def _path():
23
- return paths.DATA_DIR / "assets.json"
24
-
25
-
26
- def _load():
27
- try:
28
- value = json.loads(_path().read_text(encoding="utf-8"))
29
- return value if isinstance(value, dict) else {"assets": {}}
30
- except (OSError, ValueError):
31
- return {"assets": {}}
32
-
33
-
34
- def _save(data):
35
- path = _path()
36
- path.parent.mkdir(parents=True, exist_ok=True)
37
- tmp = path.with_suffix(".tmp")
38
- tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
39
- tmp.replace(path)
40
-
41
-
42
- def register(workdir, relative_path, *, owner_type="", owner_id="", name="", mime=""):
43
- """Index a workspace file and return its reference, or ``None`` if absent."""
44
- root = Path(str(workdir or "")).resolve()
45
- rel = str(relative_path or "").replace("\\", "/").lstrip("/")
46
- if not rel or rel.startswith("../") or "/../" in rel:
47
- return None
48
- fp = (root / rel).resolve()
49
- try:
50
- if root not in fp.parents or not fp.is_file():
51
- return None
52
- digest_builder = hashlib.sha256()
53
- size = 0
54
- with fp.open("rb") as handle:
55
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
56
- digest_builder.update(chunk)
57
- size += len(chunk)
58
- digest = digest_builder.hexdigest()
59
- asset_id = "asset-" + digest[:16]
60
- revision_id = "assetrev-" + digest[:16]
61
- ref = {"asset_id": asset_id, "revision_id": revision_id,
62
- "content_sha256": digest, "path": rel,
63
- "name": str(name or fp.name)[:120],
64
- "mime": str(mime or mimetypes.guess_type(fp.name)[0]
65
- or "application/octet-stream")[:120],
66
- "size": size, "updated_at": time.time()}
67
- with LOCK:
68
- data = _load()
69
- assets = data.setdefault("assets", {})
70
- row = assets.setdefault(asset_id, ref)
71
- # The content hash identifies one immutable revision. Keep the
72
- # first source path/name as canonical metadata so registering the
73
- # same bytes from another workspace cannot rewrite an existing
74
- # reference's path semantics.
75
- row.update({k: ref[k] for k in
76
- ("revision_id", "content_sha256", "size", "updated_at")})
77
- for key in ("path", "name", "mime"):
78
- if not row.get(key):
79
- row[key] = ref[key]
80
- owners = row.setdefault("owners", [])
81
- owner = {"type": str(owner_type or "")[:40], "id": str(owner_id or "")[:100]}
82
- if owner["id"] and owner not in owners:
83
- owners.append(owner)
84
- row["owners"] = owners[-50:]
85
- _save(data)
86
- return dict(row)
87
- except (OSError, ValueError):
88
- return None
89
-
90
-
91
- def get(asset_id, revision_id=""):
92
- with LOCK:
93
- row = (_load().get("assets") or {}).get(str(asset_id or ""))
94
- if not isinstance(row, dict):
95
- return None
96
- if revision_id and str(row.get("revision_id") or "") != str(revision_id):
97
- return None
98
- return dict(row)
99
-
100
-
101
- def list_assets(*, owner_type="", owner_id="", limit=200):
102
- with LOCK:
103
- rows = list((_load().get("assets") or {}).values())
104
- if owner_type or owner_id:
105
- rows = [row for row in rows if any(
106
- (not owner_type or owner_type == item.get("type")) and
107
- (not owner_id or owner_id == item.get("id"))
108
- for item in (row.get("owners") or []))]
109
- rows.sort(key=lambda row: float(row.get("updated_at") or 0), reverse=True)
110
- return [dict(row) for row in rows[:max(1, min(1000, int(limit or 200)))]]
1
+ # -*- coding: utf-8 -*-
2
+ """Content-addressed asset index.
3
+
4
+ The index owns references and revisions, not file contents. Files stay in the
5
+ task workspace; projects/runs can safely point to ``asset_id + revision_id``
6
+ without making a second copy of a document.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import hashlib
12
+ import mimetypes
13
+ import threading
14
+ import time
15
+ from pathlib import Path
16
+
17
+ from . import paths
18
+
19
+ LOCK = threading.RLock()
20
+
21
+
22
+ def _path():
23
+ return paths.DATA_DIR / "assets.json"
24
+
25
+
26
+ def _load():
27
+ try:
28
+ value = json.loads(_path().read_text(encoding="utf-8"))
29
+ return value if isinstance(value, dict) else {"assets": {}}
30
+ except (OSError, ValueError):
31
+ return {"assets": {}}
32
+
33
+
34
+ def _save(data):
35
+ path = _path()
36
+ path.parent.mkdir(parents=True, exist_ok=True)
37
+ tmp = path.with_suffix(".tmp")
38
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
39
+ tmp.replace(path)
40
+
41
+
42
+ def register(workdir, relative_path, *, owner_type="", owner_id="", name="", mime=""):
43
+ """Index a workspace file and return its reference, or ``None`` if absent."""
44
+ root = Path(str(workdir or "")).resolve()
45
+ rel = str(relative_path or "").replace("\\", "/").lstrip("/")
46
+ if not rel or rel.startswith("../") or "/../" in rel:
47
+ return None
48
+ fp = (root / rel).resolve()
49
+ try:
50
+ if root not in fp.parents or not fp.is_file():
51
+ return None
52
+ digest_builder = hashlib.sha256()
53
+ size = 0
54
+ with fp.open("rb") as handle:
55
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
56
+ digest_builder.update(chunk)
57
+ size += len(chunk)
58
+ digest = digest_builder.hexdigest()
59
+ asset_id = "asset-" + digest[:16]
60
+ revision_id = "assetrev-" + digest[:16]
61
+ ref = {"asset_id": asset_id, "revision_id": revision_id,
62
+ "content_sha256": digest, "path": rel,
63
+ "name": str(name or fp.name)[:120],
64
+ "mime": str(mime or mimetypes.guess_type(fp.name)[0]
65
+ or "application/octet-stream")[:120],
66
+ "size": size, "updated_at": time.time()}
67
+ with LOCK:
68
+ data = _load()
69
+ assets = data.setdefault("assets", {})
70
+ row = assets.setdefault(asset_id, ref)
71
+ # The content hash identifies one immutable revision. Keep the
72
+ # first source path/name as canonical metadata so registering the
73
+ # same bytes from another workspace cannot rewrite an existing
74
+ # reference's path semantics.
75
+ row.update({k: ref[k] for k in
76
+ ("revision_id", "content_sha256", "size", "updated_at")})
77
+ for key in ("path", "name", "mime"):
78
+ if not row.get(key):
79
+ row[key] = ref[key]
80
+ owners = row.setdefault("owners", [])
81
+ owner = {"type": str(owner_type or "")[:40], "id": str(owner_id or "")[:100]}
82
+ if owner["id"] and owner not in owners:
83
+ owners.append(owner)
84
+ row["owners"] = owners[-50:]
85
+ _save(data)
86
+ return dict(row)
87
+ except (OSError, ValueError):
88
+ return None
89
+
90
+
91
+ def get(asset_id, revision_id=""):
92
+ with LOCK:
93
+ row = (_load().get("assets") or {}).get(str(asset_id or ""))
94
+ if not isinstance(row, dict):
95
+ return None
96
+ if revision_id and str(row.get("revision_id") or "") != str(revision_id):
97
+ return None
98
+ return dict(row)
99
+
100
+
101
+ def list_assets(*, owner_type="", owner_id="", limit=200):
102
+ with LOCK:
103
+ rows = list((_load().get("assets") or {}).values())
104
+ if owner_type or owner_id:
105
+ rows = [row for row in rows if any(
106
+ (not owner_type or owner_type == item.get("type")) and
107
+ (not owner_id or owner_id == item.get("id"))
108
+ for item in (row.get("owners") or []))]
109
+ rows.sort(key=lambda row: float(row.get("updated_at") or 0), reverse=True)
110
+ return [dict(row) for row in rows[:max(1, min(1000, int(limit or 200)))]]