codebee 0.1.95 → 0.1.96

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 (138) hide show
  1. package/CHANGELOG.md +725 -720
  2. package/LICENSE +21 -21
  3. package/README.md +515 -509
  4. package/app/core/acceptance.py +100 -100
  5. package/app/core/agent_context.py +100 -0
  6. package/app/core/aiflavor.py +197 -197
  7. package/app/core/analytics.py +38 -38
  8. package/app/core/artifacts.py +148 -148
  9. package/app/core/assets.py +110 -110
  10. package/app/core/attachments.py +623 -623
  11. package/app/core/audit.py +30 -30
  12. package/app/core/backup.py +470 -470
  13. package/app/core/beekeeper.py +183 -183
  14. package/app/core/benchstore.py +102 -95
  15. package/app/core/board.py +209 -209
  16. package/app/core/bookmeta.py +1036 -1036
  17. package/app/core/bookmeta_catalog.py +180 -180
  18. package/app/core/branching.py +137 -137
  19. package/app/core/builtin_agent.py +1680 -1680
  20. package/app/core/capability.py +144 -144
  21. package/app/core/chaptersafe.py +32 -32
  22. package/app/core/checkpoints.py +143 -0
  23. package/app/core/cleanup.py +303 -303
  24. package/app/core/compaction.py +201 -201
  25. package/app/core/contracts.py +255 -255
  26. package/app/core/covergen.py +356 -356
  27. package/app/core/defectretro.py +43 -43
  28. package/app/core/diagnostics.py +114 -114
  29. package/app/core/dispatch.py +198 -191
  30. package/app/core/dispatch_log.py +128 -128
  31. package/app/core/env_scrub.py +85 -85
  32. package/app/core/errorlog.py +137 -137
  33. package/app/core/eval_matrix.py +82 -0
  34. package/app/core/evalbench.py +184 -91
  35. package/app/core/evaluation.py +174 -174
  36. package/app/core/failure_notify.py +290 -290
  37. package/app/core/flow_graph.py +33 -0
  38. package/app/core/goal_service.py +167 -167
  39. package/app/core/health.py +389 -389
  40. package/app/core/history.py +38 -38
  41. package/app/core/hooks.py +162 -162
  42. package/app/core/jobs.py +25 -4
  43. package/app/core/knowledge_pipeline.py +86 -0
  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 +181 -189
  48. package/app/core/openapi.py +177 -154
  49. package/app/core/operations.py +228 -228
  50. package/app/core/paihang.py +145 -145
  51. package/app/core/pipeline.py +43 -19
  52. package/app/core/planner.py +17 -11
  53. package/app/core/policy.py +52 -0
  54. package/app/core/portguard.py +111 -111
  55. package/app/core/presence.py +77 -77
  56. package/app/core/preview.py +293 -293
  57. package/app/core/prompt_guard.py +78 -78
  58. package/app/core/publish/__init__.py +7 -7
  59. package/app/core/publish/auto.py +26 -3
  60. package/app/core/publish/browser.py +655 -655
  61. package/app/core/publish/chaprows.py +138 -0
  62. package/app/core/publish/fanqie.py +210 -165
  63. package/app/core/publish/flow.py +753 -640
  64. package/app/core/publish/flows-fanqie-calibrated.json +349 -336
  65. package/app/core/publish/ledger.py +13 -1
  66. package/app/core/publish/manager.py +1150 -1118
  67. package/app/core/publish/qimao.py +176 -176
  68. package/app/core/publish/volumes.py +108 -0
  69. package/app/core/publish/ws.py +139 -139
  70. package/app/core/quality_gate.py +194 -194
  71. package/app/core/redact.py +38 -38
  72. package/app/core/repeat_guard.py +129 -129
  73. package/app/core/retrieval.py +137 -137
  74. package/app/core/router.py +398 -398
  75. package/app/core/runner.py +2238 -2238
  76. package/app/core/selfupdate.py +384 -384
  77. package/app/core/session_log.py +161 -161
  78. package/app/core/sessions.py +312 -312
  79. package/app/core/settings.py +20 -0
  80. package/app/core/settings_schema.py +270 -270
  81. package/app/core/share_page.py +114 -114
  82. package/app/core/skill_scan.py +139 -139
  83. package/app/core/skillpacks/fanqie-novel.md +8 -6
  84. package/app/core/skillpacks/market/character-bible.md +66 -66
  85. package/app/core/skillpacks/market/code-risk-checklist.md +58 -58
  86. package/app/core/skillpacks/market/git-workflow.md +57 -57
  87. package/app/core/skillpacks/market/release-notes.md +72 -72
  88. package/app/core/skillpacks/market/weekly-report.md +71 -71
  89. package/app/core/skillpacks/market/worldview-consistency.md +70 -70
  90. package/app/core/skillpacks/qimao-signing.md +14 -11
  91. package/app/core/skills.py +32 -21
  92. package/app/core/step_runner.py +132 -132
  93. package/app/core/store.py +9 -0
  94. package/app/core/story_tracking.py +275 -275
  95. package/app/core/task_compile.py +199 -199
  96. package/app/core/telemetry.py +292 -292
  97. package/app/core/tlsctx.py +64 -64
  98. package/app/core/token_meter.py +147 -147
  99. package/app/core/tracing.py +207 -144
  100. package/app/core/upstream.py +41 -41
  101. package/app/core/usage.py +1038 -1038
  102. package/app/core/volumes.py +389 -389
  103. package/app/core/webhooks.py +89 -0
  104. package/app/core/wxdigest.py +858 -858
  105. package/app/core/zentao.py +2692 -2692
  106. package/app/main.py +104 -9
  107. package/app/mcp_server.py +244 -244
  108. package/app/pick_dialog.py +110 -110
  109. package/app/ui/app.js +286 -18
  110. package/app/ui/artdiff.js +74 -74
  111. package/app/ui/assets/community-qr.png +0 -0
  112. package/app/ui/assets/donate-alipay.jpg +0 -0
  113. package/app/ui/assets/donate-qr.jpg +0 -0
  114. package/app/ui/board.html +162 -162
  115. package/app/ui/board.js +305 -305
  116. package/app/ui/i18n.js +33 -0
  117. package/app/ui/icons/bee.svg +79 -79
  118. package/app/ui/index.html +32 -3
  119. package/app/ui/manifest.json +16 -16
  120. package/app/ui/qrcode.js +2297 -2297
  121. package/app/ui/style.css +196 -2
  122. package/bin/tutti.js +147 -147
  123. package/package.json +48 -48
  124. package/tools/wx_reader.py +261 -261
  125. package/app/.playwright-cli/console-2026-09-23T08-26-03-635Z.log +0 -88
  126. package/app/.playwright-cli/page-2026-09-23T08-26-03-845Z.yml +0 -126
  127. package/app/.playwright-cli/page-2026-09-23T08-29-44-203Z.png +0 -0
  128. package/app/.playwright-cli/page-2026-09-23T08-35-42-046Z.yml +0 -210
  129. package/app/.playwright-cli/page-2026-09-23T08-36-52-858Z.png +0 -0
  130. package/app/.playwright-cli/page-2026-09-23T08-37-33-938Z.png +0 -0
  131. package/app/.playwright-cli/run-detail-after.png +0 -0
  132. package/app/output/_createbook_body.json +0 -1
  133. package/app/output/_probe_fq_click.py +0 -50
  134. package/app/output/_probe_fq_form.py +0 -42
  135. package/app/output/_probe_fq_modal.py +0 -55
  136. package/app/output/_probe_fq_points.py +0 -71
  137. package/app/output/_probe_fq_submit.py +0 -34
  138. package/app/output/_probe_fq_watch.py +0 -62
@@ -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)))]]