fuli-context 0.20.0-beta.13 → 0.20.0-beta.15

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 (62) hide show
  1. package/dist/web/assets/{index-DvkJiX-L.js → index-GEnfRzSe.js} +1 -1
  2. package/dist/web/index.html +1 -1
  3. package/graph-provider/fuli_graph/app.py +16 -11
  4. package/graph-provider/fuli_graph/graph_query.py +30 -2
  5. package/graph-provider/fuli_graph/knowledge_audit.py +9 -1
  6. package/graph-provider/fuli_graph/knowledge_item_routes.py +10 -6
  7. package/graph-provider/fuli_graph/knowledge_item_view.py +41 -12
  8. package/graph-provider/fuli_graph/knowledge_item_view_models.py +3 -3
  9. package/graph-provider/fuli_graph/knowledge_review.py +47 -10
  10. package/graph-provider/fuli_graph/knowledge_search.py +18 -22
  11. package/graph-provider/fuli_graph/knowledge_session_migration.py +14 -4
  12. package/graph-provider/fuli_graph/knowledge_session_migration_models.py +2 -2
  13. package/graph-provider/fuli_graph/knowledge_tag_routes.py +7 -5
  14. package/graph-provider/fuli_graph/knowledge_tags.py +8 -4
  15. package/graph-provider/fuli_graph/knowledge_visibility.py +195 -0
  16. package/graph-provider/fuli_graph/models.py +12 -2
  17. package/graph-provider/fuli_graph/preference_conflicts.py +50 -4
  18. package/graph-provider/fuli_graph/publication_source_copies.py +36 -0
  19. package/graph-provider/fuli_graph/session_records.py +33 -13
  20. package/graph-provider/fuli_graph/session_records_models.py +4 -2
  21. package/graph-provider/fuli_graph/store_knowledge.py +5 -1
  22. package/graph-provider/fuli_graph/store_publication.py +70 -12
  23. package/graph-provider/pyproject.toml +1 -1
  24. package/native/win32/fuli-win-helper.exe +0 -0
  25. package/npm-shrinkwrap.json +2 -2
  26. package/package.json +1 -1
  27. package/skills/capturing-session-knowledge/references/retrieval.md +6 -0
  28. package/src/agent-tools/graph-definitions.js +4 -4
  29. package/src/agent-tools/interface-definitions.js +2 -1
  30. package/src/agent-tools/session-fuli-gate.js +55 -26
  31. package/src/agent-tools.js +2 -4
  32. package/src/agents/claude-code/lifecycle-hook.js +4 -3
  33. package/src/agents/codex/lifecycle-hook.js +4 -3
  34. package/src/agents/lifecycle-message.js +18 -0
  35. package/src/agents/turn-receipt.js +15 -8
  36. package/src/app/agent-request-context.js +18 -0
  37. package/src/graphiti/capture-notice.js +4 -1
  38. package/src/graphiti/federated-application.js +49 -60
  39. package/src/graphiti/human-review-channel.js +9 -5
  40. package/src/graphiti/knowledge-item-edit.js +7 -4
  41. package/src/graphiti/knowledge-reader.js +46 -0
  42. package/src/graphiti/knowledge-result-budget.js +63 -12
  43. package/src/graphiti/knowledge-tags.js +12 -1
  44. package/src/graphiti/provider-client.js +13 -21
  45. package/src/graphiti/publication-draft-capture.js +28 -0
  46. package/src/graphiti/session-knowledge-migration.js +7 -3
  47. package/src/graphiti/session-layer-decision.js +28 -6
  48. package/src/graphiti/session-records.js +26 -15
  49. package/src/graphiti/turn-receipt-delivery.js +5 -2
  50. package/src/graphiti/writing-taste-profile-workflow.js +13 -7
  51. package/src/http/api-router.js +2 -1
  52. package/src/http/graph-api-router.js +13 -10
  53. package/src/http/knowledge-item-api-router.js +17 -4
  54. package/src/http/knowledge-tags-api-router.js +21 -9
  55. package/src/http/session-records-api-router.js +7 -3
  56. package/src/knowledge-owner-reads/console-port.js +51 -0
  57. package/src/knowledge-tags/console-port.js +3 -2
  58. package/src/mcp/preference-delivery.js +7 -4
  59. package/src/mcp/provider-task-context-registry.js +15 -0
  60. package/src/mcp/tool-result.js +3 -3
  61. package/src/presence/windows-helper-pin.js +1 -1
  62. package/src/server.js +8 -1
@@ -0,0 +1,195 @@
1
+ """Who may read FLA-scoped knowledge.
2
+
3
+ Knowledge an FLA's own episodes wrote, and a preference the person gave one
4
+ FLA, belong to that FLA in its project, and to the person. Search, the graph
5
+ read, item views, turn receipts, session records, the human-change search,
6
+ the AI review and its decisions, preference conflicts and a session's
7
+ migration preview all decide it here.
8
+
9
+ The person's console proves itself with the human-review channel and reads
10
+ everything. Any other reader is an Agent: one FLA in one project, or a plain
11
+ session that is no FLA. No proof means an Agent reader, never a full read; a
12
+ wrong proof is refused before any read (app.current_review_aware_actor), and
13
+ a reader naming an FLA that is not assigned to that project is refused here.
14
+ """
15
+ from dataclasses import dataclass
16
+
17
+ from .project_agent_access import authorize_project_agent
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class AgentReader:
22
+ personal_project_id: str | None = None
23
+ project_agent_id: str | None = None
24
+
25
+
26
+ PLAIN_SESSION = AgentReader()
27
+
28
+
29
+ async def knowledge_reader(store, actor: dict, space: dict, *, personal_project_id: str | None,
30
+ project_agent_id: str | None) -> AgentReader | None:
31
+ """None for the person's console (full read), else the Agent reading."""
32
+ if actor.get('_human_review_verified') is True:
33
+ return None
34
+ if not project_agent_id:
35
+ return PLAIN_SESSION
36
+ agent = await authorize_project_agent(store, actor, space, personal_project_id, project_agent_id)
37
+ return AgentReader(personal_project_id, agent['agent_id'])
38
+
39
+
40
+ async def request_reader(store, actor: dict, space: dict, request) -> AgentReader | None:
41
+ """knowledge_reader for a request with reader_project_id and reader_agent_id."""
42
+ return await knowledge_reader(store, actor, space, personal_project_id=request.reader_project_id,
43
+ project_agent_id=request.reader_agent_id)
44
+
45
+
46
+ def fla_visible(record: dict, reader: AgentReader) -> bool:
47
+ """Whether this reader may see the item. record carries profile_aspect,
48
+ preference_scope, preference_project_id, preference_agent_id and, from
49
+ the item's own episodes, episode_project_ids and episode_project_agent_ids.
50
+ A preference follows its own scope only; other knowledge any FLA's
51
+ episode wrote belongs to that FLA in that project. A relationship's
52
+ record also carries endpoints_visible (fla_endpoints_visible_cypher): one
53
+ linking to an entity this reader may not see is hidden with it."""
54
+ if record.get('endpoints_visible') is False:
55
+ return False
56
+ if record.get('profile_aspect'):
57
+ if (record.get('preference_scope') or 'global') != 'agent':
58
+ return True
59
+ return (
60
+ bool(reader.project_agent_id)
61
+ and record.get('preference_agent_id') == reader.project_agent_id
62
+ and record.get('preference_project_id') == reader.personal_project_id
63
+ )
64
+ agent_ids = record.get('episode_project_agent_ids') or []
65
+ if not agent_ids:
66
+ return True
67
+ return (
68
+ bool(reader.project_agent_id)
69
+ and reader.project_agent_id in agent_ids
70
+ and reader.personal_project_id in (record.get('episode_project_ids') or [])
71
+ )
72
+
73
+
74
+ def fla_visible_cypher(item: str, item_kind: str) -> str:
75
+ """fla_visible as a Cypher predicate on the bound `item` (an Entity, or a
76
+ RELATES_TO edge), so a page is cut after hiding and shows no gap. Needs
77
+ $group_id and $reader (reader_parameter: null for the person)."""
78
+ def episodes(condition: str) -> str:
79
+ if item_kind == 'entity':
80
+ return (f'EXISTS {{ MATCH (fla_episode:Episodic {{group_id: $group_id}})-[:MENTIONS]->({item}) '
81
+ f'WHERE {condition} }}')
82
+ return (f'EXISTS {{ MATCH (fla_episode:Episodic {{group_id: $group_id}}) '
83
+ f'WHERE fla_episode.uuid IN coalesce({item}.episodes, []) AND {condition} }}')
84
+
85
+ return f'''($reader IS NULL OR coalesce(
86
+ CASE WHEN {item}.fuli_profile_aspect IS NOT NULL
87
+ THEN coalesce({item}.fuli_preference_scope, 'global') <> 'agent'
88
+ OR ({item}.fuli_preference_agent_id = $reader.project_agent_id
89
+ AND {item}.fuli_preference_project_id = $reader.personal_project_id)
90
+ ELSE NOT {episodes('fla_episode.fuli_project_agent_id IS NOT NULL')}
91
+ OR ({episodes('fla_episode.fuli_project_agent_id = $reader.project_agent_id')}
92
+ AND {episodes('fla_episode.fuli_personal_project_id = $reader.personal_project_id')})
93
+ END, false))'''
94
+
95
+
96
+ def fla_relationship_visible_cypher(edge: str, source: str, target: str) -> str:
97
+ """A relationship is visible only with both its endpoints: one that links
98
+ to another FLA's entity is hidden with it, wherever it is read (graph,
99
+ item view, receipt, session records; search and the AI review through
100
+ fla_endpoints_visible_cypher and fla_visible)."""
101
+ return f"({fla_visible_cypher(edge, 'relationship')} AND {fla_endpoints_visible_cypher(source, target)})"
102
+
103
+
104
+ def fla_endpoints_visible_cypher(source: str, target: str) -> str:
105
+ """Whether this reader may see both endpoints of a relationship. Needs
106
+ $group_id and $reader."""
107
+ return f"({fla_visible_cypher(source, 'entity')} AND {fla_visible_cypher(target, 'entity')})"
108
+
109
+
110
+ def fla_own_work_cypher(agent: str, project: str) -> str:
111
+ """Work done under an FLA (a session's turn, or an episode it wrote) is
112
+ that FLA's conversation: an FLA reads its own in its project, a plain
113
+ session only work under no FLA, and only the person all of it. agent and
114
+ project are the Cypher expressions of that work's FLA and project. Needs
115
+ $reader."""
116
+ return f'''($reader IS NULL OR CASE WHEN $reader.project_agent_id IS NULL
117
+ THEN {agent} IS NULL
118
+ ELSE coalesce({agent} = $reader.project_agent_id
119
+ AND {project} = $reader.personal_project_id, false) END)'''
120
+
121
+
122
+ def fla_visible_ids_cypher(item_ids: str) -> str:
123
+ """True when no entity or relationship among item_ids (a Cypher list
124
+ expression) is hidden from $reader: a record naming another FLA's item
125
+ is left out with it. Needs $group_id and $reader."""
126
+ return (f'''($reader IS NULL OR (
127
+ NOT EXISTS {{ MATCH (fla_item:Entity {{group_id: $group_id}}) WHERE fla_item.uuid IN {item_ids}
128
+ AND NOT {fla_visible_cypher('fla_item', 'entity')} }}
129
+ AND NOT EXISTS {{ MATCH (fla_source:Entity)-[fla_item:RELATES_TO {{group_id: $group_id}}]->(fla_target:Entity)
130
+ WHERE fla_item.uuid IN {item_ids}
131
+ AND NOT {fla_relationship_visible_cypher('fla_item', 'fla_source', 'fla_target')} }}))''')
132
+
133
+
134
+ def fla_episode_visible_cypher(episode: str) -> str:
135
+ """An episode an FLA wrote, as evidence or as a session's source: only
136
+ that FLA in its project reads it. Needs $reader."""
137
+ return f'''($reader IS NULL OR {episode}.fuli_project_agent_id IS NULL
138
+ OR coalesce({episode}.fuli_project_agent_id = $reader.project_agent_id
139
+ AND {episode}.fuli_personal_project_id = $reader.personal_project_id, false))'''
140
+
141
+
142
+ def reader_parameter(reader: AgentReader | None) -> dict | None:
143
+ if reader is None:
144
+ return None
145
+ return {'personal_project_id': reader.personal_project_id, 'project_agent_id': reader.project_agent_id}
146
+
147
+
148
+ _HIDDEN_QUERIES = {
149
+ 'entity': '''
150
+ MATCH (item:Entity {group_id: $group_id}) WHERE item.uuid IN $item_ids
151
+ AND NOT ''' + fla_visible_cypher('item', 'entity') + '''
152
+ RETURN item.uuid AS id''',
153
+ 'relationship': '''
154
+ MATCH (source)-[item:RELATES_TO {group_id: $group_id}]->(target)
155
+ WHERE item.uuid IN $item_ids
156
+ AND NOT ''' + fla_relationship_visible_cypher('item', 'source', 'target') + '''
157
+ RETURN item.uuid AS id''',
158
+ }
159
+
160
+
161
+ async def _hidden_items(store, space: dict, reader: AgentReader | None, item_kind: str,
162
+ item_ids) -> set[str]:
163
+ """The ids among these that this reader may not see."""
164
+ item_ids = list(dict.fromkeys(item_ids))
165
+ if reader is None or not item_ids:
166
+ return set()
167
+ records, _, _ = await store.runtime.driver.execute_query(
168
+ _HIDDEN_QUERIES[item_kind], group_id=space['group_id'], item_ids=item_ids,
169
+ reader=reader_parameter(reader), routing_='r')
170
+ return {record['id'] for record in records}
171
+
172
+
173
+ async def hidden_refs(store, space: dict, reader: AgentReader | None, refs) -> set[tuple[str, str]]:
174
+ """The (item_kind, item_id) pairs among these that this reader may not see."""
175
+ refs = list(refs)
176
+ hidden = set()
177
+ for item_kind in _HIDDEN_QUERIES:
178
+ ids = [item_id for kind, item_id in refs if kind == item_kind]
179
+ hidden |= {(item_kind, item_id) for item_id in await _hidden_items(store, space, reader, item_kind, ids)}
180
+ return hidden
181
+
182
+
183
+ async def visible_episode_ids(store, space: dict, reader: AgentReader | None, episode_ids) -> list[str]:
184
+ """These episodes in order, without the ones another FLA wrote."""
185
+ episode_ids = list(episode_ids)
186
+ if reader is None or not episode_ids:
187
+ return episode_ids
188
+ records, _, _ = await store.runtime.driver.execute_query(
189
+ '''
190
+ MATCH (episode:Episodic {group_id: $group_id}) WHERE episode.uuid IN $episode_ids
191
+ AND NOT ''' + fla_episode_visible_cypher('episode') + '''
192
+ RETURN episode.uuid AS id
193
+ ''', group_id=space['group_id'], episode_ids=episode_ids, reader=reader_parameter(reader), routing_='r')
194
+ hidden = {record['id'] for record in records}
195
+ return [episode_id for episode_id in episode_ids if episode_id not in hidden]
@@ -997,7 +997,17 @@ class CollaborationContextResult(StrictModel):
997
997
  truncated: bool = False
998
998
 
999
999
 
1000
- class PreferenceConflictDeferCreate(StrictModel):
1000
+ class AgentReaderRef(StrictModel):
1001
+ """The Agent reading: an FLA in its project, or neither for a plain
1002
+ session. The person's console names no reader; it proves itself with the
1003
+ human-review channel instead (knowledge_visibility)."""
1004
+ reader_project_id: str | None = Field(default=None, min_length=1, max_length=128)
1005
+ reader_agent_id: str | None = Field(default=None, min_length=1, max_length=128)
1006
+
1007
+
1008
+ # A conflict's write names its reader too: one naming an item this reader may
1009
+ # not see answers as missing, before anything is written or returned (0.20.1).
1010
+ class PreferenceConflictDeferCreate(AgentReaderRef):
1001
1011
  personal_space_id: str = Field(min_length=1, max_length=128)
1002
1012
  conflict_id: str = Field(min_length=1, max_length=1024)
1003
1013
  preference_key: str = Field(min_length=1, max_length=512)
@@ -1024,7 +1034,7 @@ class PreferenceConflictDeferCreate(StrictModel):
1024
1034
  return self
1025
1035
 
1026
1036
 
1027
- class PreferenceConflictResolveCreate(StrictModel):
1037
+ class PreferenceConflictResolveCreate(AgentReaderRef):
1028
1038
  personal_space_id: str = Field(min_length=1, max_length=128)
1029
1039
  resolution: PreferenceConflictResolutionAction
1030
1040
  reason: str = Field(min_length=1, max_length=2000)
@@ -16,6 +16,13 @@ from .models import (
16
16
  PreferenceConflictResolveCreate,
17
17
  PreferenceScopeChange,
18
18
  )
19
+ from .knowledge_visibility import (
20
+ fla_visible_ids_cypher,
21
+ hidden_refs,
22
+ knowledge_reader,
23
+ reader_parameter,
24
+ request_reader,
25
+ )
19
26
  from .provider_values import native_datetime as _native_datetime
20
27
 
21
28
 
@@ -42,6 +49,14 @@ async def defer_preference_conflict(
42
49
  request.personal_space_id,
43
50
  'maintainer',
44
51
  )
52
+ # Neither the items it names nor a conflict already kept under this id
53
+ # may be another FLA's: that answers as missing, and nothing is written.
54
+ reader = await request_reader(store, actor, space, request)
55
+ if reader is not None:
56
+ existing = await _stored_conflict(store, space['id'], request.conflict_id)
57
+ await _require_visible(store, space, reader, [
58
+ (request.left_item_kind, request.left_item_id), (request.right_item_kind, request.right_item_id),
59
+ *(_conflict_items(existing) if existing else [])])
45
60
  left = await _active_preference_item(
46
61
  store,
47
62
  space,
@@ -140,23 +155,30 @@ async def list_preference_conflicts(
140
155
  limit: int = 500,
141
156
  offset: int = 0,
142
157
  ) -> list[PreferenceConflictRecord]:
143
- await _authorize_personal_space(
158
+ space = await _authorize_personal_space(
144
159
  store,
145
160
  actor,
146
161
  personal_space_id,
147
162
  'reader',
148
163
  )
164
+ # An Agent reads as a plain session: no conflict naming any FLA's own
165
+ # item (an FLA meets those over its own preferences in its task context).
166
+ # The console reads them all with the human-review proof. Cut before the page.
167
+ reader = await knowledge_reader(store, actor, space, personal_project_id=None, project_agent_id=None)
149
168
  records, _, _ = await store.runtime.driver.execute_query(
150
169
  '''
151
170
  MATCH (:FuliSpace {id: $space_id, kind: 'personal'})-
152
171
  [:HAS_PREFERENCE_CONFLICT]->(conflict:FuliPreferenceConflict)
153
- WHERE $status IS NULL OR conflict.status = $status
172
+ WHERE ($status IS NULL OR conflict.status = $status)
173
+ AND ''' + fla_visible_ids_cypher('[conflict.left_item_id, conflict.right_item_id]') + '''
154
174
  RETURN conflict
155
175
  ORDER BY conflict.updated_at DESC, conflict.id ASC
156
176
  SKIP $offset
157
177
  LIMIT $limit
158
178
  ''',
159
179
  space_id=personal_space_id,
180
+ group_id=space['group_id'],
181
+ reader=reader_parameter(reader),
160
182
  status=status,
161
183
  limit=min(max(limit, 1), 1000),
162
184
  offset=max(offset, 0),
@@ -216,6 +238,10 @@ async def resolve_preference_conflict(
216
238
  'maintainer',
217
239
  )
218
240
  conflict = await _read_conflict(store, space['id'], conflict_id)
241
+ # Before anything is returned, a resolved retry included: a conflict
242
+ # naming another FLA's item answers as missing.
243
+ await _require_visible(store, space, await request_reader(store, actor, space, request),
244
+ _conflict_items(conflict))
219
245
  if conflict.status == 'resolved':
220
246
  return conflict
221
247
  if conflict.status != 'ai_pending':
@@ -266,6 +292,10 @@ async def complete_preference_conflict(
266
292
  'maintainer',
267
293
  )
268
294
  conflict = await _read_conflict(store, space['id'], conflict_id)
295
+ # The person completes any conflict with the console's proof; without it
296
+ # the caller reads as a plain session.
297
+ await _require_visible(store, space, await knowledge_reader(
298
+ store, actor, space, personal_project_id=None, project_agent_id=None), _conflict_items(conflict))
269
299
  return await _complete(
270
300
  store,
271
301
  space['id'],
@@ -467,6 +497,13 @@ async def _complete(
467
497
 
468
498
 
469
499
  async def _read_conflict(store, space_id, conflict_id):
500
+ conflict = await _stored_conflict(store, space_id, conflict_id)
501
+ if conflict is None:
502
+ raise HTTPException(status_code=404, detail='preference conflict not found')
503
+ return conflict
504
+
505
+
506
+ async def _stored_conflict(store, space_id, conflict_id):
470
507
  records, _, _ = await store.runtime.driver.execute_query(
471
508
  '''
472
509
  MATCH (:FuliSpace {id: $space_id, kind: 'personal'})-
@@ -478,9 +515,18 @@ async def _read_conflict(store, space_id, conflict_id):
478
515
  conflict_id=conflict_id,
479
516
  routing_='r',
480
517
  )
481
- if not records:
518
+ return _record(records[0]['conflict']) if records else None
519
+
520
+
521
+ def _conflict_items(conflict) -> list[tuple[str, str]]:
522
+ return [(conflict.left_item_kind, conflict.left_item_id),
523
+ (conflict.right_item_kind, conflict.right_item_id)]
524
+
525
+
526
+ async def _require_visible(store, space, reader, items) -> None:
527
+ """A conflict naming an item this reader may not see is, to it, missing."""
528
+ if await hidden_refs(store, space, reader, items):
482
529
  raise HTTPException(status_code=404, detail='preference conflict not found')
483
- return _record(records[0]['conflict'])
484
530
 
485
531
 
486
532
  async def _active_preference_item(store, space, item_id, item_kind):
@@ -21,6 +21,42 @@ def publication_source_identity(group_id, episode):
21
21
  return identity
22
22
 
23
23
 
24
+ PROJECT_AGENT, PLAIN, UNRESOLVED = 'project_agent', 'plain', 'unresolved'
25
+
26
+
27
+ async def draft_sources(store, space, identities) -> list[str]:
28
+ """Whose work each of these draft source identities is, from the personal
29
+ episode it names and the session turn it came from (0.20.1):
30
+ PROJECT_AGENT when either is an FLA's, PLAIN only when one of them is
31
+ found and neither is, and UNRESOLVED when neither is found (erased, or
32
+ never recorded, as for a capture made only for a team project). Nothing
33
+ is ever taken as plain for want of a source."""
34
+ sources = [{'index': index, 'episode_id': identity.get('episode_id'),
35
+ 'turn_id': identity.get('source_turn_id'),
36
+ 'session_node': store._task_session_id(space['id'], identity['source_application'],
37
+ identity['session_id'])
38
+ if identity.get('source_application') and identity.get('session_id') else None}
39
+ for index, identity in enumerate(identities)]
40
+ if not sources:
41
+ return []
42
+ records, _, _ = await store.runtime.driver.execute_query(
43
+ '''
44
+ UNWIND $sources AS source
45
+ OPTIONAL MATCH (episode:Episodic {group_id: $group_id, uuid: source.episode_id})
46
+ OPTIONAL MATCH (:FuliSpace {id: $space_id, kind: 'personal'})-[:HAS_TASK_CONTEXT_SESSION]->
47
+ (:FuliTaskContextSession {id: source.session_node})-[:HAS_CONTEXT]->
48
+ (task:FuliTaskContext {turn_id: source.turn_id})
49
+ WITH source, collect(DISTINCT episode) AS episodes, collect(DISTINCT task) AS tasks
50
+ RETURN source.index AS index,
51
+ any(episode IN episodes WHERE episode.fuli_project_agent_id IS NOT NULL)
52
+ OR any(task IN tasks WHERE task.project_agent_id IS NOT NULL) AS project_agent,
53
+ size(episodes) + size(tasks) > 0 AS found
54
+ ''', sources=sources, group_id=space['group_id'], space_id=space['id'], routing_='r')
55
+ found = {record['index']: (PROJECT_AGENT if record['project_agent'] else PLAIN if record['found'] else UNRESOLVED)
56
+ for record in records}
57
+ return [found.get(index, UNRESOLVED) for index in range(len(sources))]
58
+
59
+
24
60
  async def drafts_for_sources(store, space, sources, *, source_range=None):
25
61
  """Read copies by exact source identity; all statuses participate in erasure.
26
62
  Legacy drafts derive their identity from payload until first scrubbed.
@@ -22,6 +22,13 @@ from .knowledge_item_view import (
22
22
  scope_projects,
23
23
  )
24
24
  from .knowledge_management import _read_item
25
+ from .knowledge_visibility import (
26
+ fla_episode_visible_cypher,
27
+ fla_own_work_cypher,
28
+ hidden_refs,
29
+ reader_parameter,
30
+ request_reader,
31
+ )
25
32
  from .models import SourceApplication
26
33
  from .provider_values import native_datetime
27
34
  from .session_records_models import (
@@ -55,15 +62,19 @@ NOT_RECORDED_EVENT = re.compile(r':not_recorded$')
55
62
 
56
63
  async def read_session_records(store, actor: dict, request: SessionRecordsRead) -> SessionRecords:
57
64
  space = await personal_reader_space(store, actor, request.personal_space_id)
65
+ # An Agent reads only the turns of its own FLA (a plain session: turns
66
+ # under no FLA), and none of another FLA's episodes or items. Each is cut
67
+ # before its page, so neither a count nor a gap shows what was left out.
68
+ reader = await request_reader(store, actor, space, request)
58
69
  if request.source_application is None:
59
70
  clients = await _session_clients(store, space, request.session_id)
60
71
  if len(clients) != 1:
61
72
  return SessionRecords(session_id=request.session_id, clients=clients)
62
73
  request = request.model_copy(update={'source_application': clients[0]})
63
- tasks, more_turns = await _session_tasks(store, space, request)
74
+ tasks, more_turns = await _session_tasks(store, space, request, reader)
64
75
  turns, more_events = await _turns(store, space, tasks)
65
- episodes, more_episodes = await _session_episodes(store, space, request, tasks)
66
- items, more_items = await _items(store, space, episodes)
76
+ episodes, more_episodes = await _session_episodes(store, space, request, tasks, reader)
77
+ items, more_items = await _items(store, space, episodes, reader)
67
78
  project_ids = {turn.personal_project_id for turn in turns} | {item.origin_project_id for item in items}
68
79
  return SessionRecords(
69
80
  session_id=request.session_id, source_application=request.source_application,
@@ -89,16 +100,17 @@ async def _session_clients(store, space, session_id):
89
100
  return sorted(nodes[record['id']] for record in records)
90
101
 
91
102
 
92
- async def _session_tasks(store, space, request):
103
+ async def _session_tasks(store, space, request, reader):
93
104
  records, _, _ = await store.runtime.driver.execute_query(
94
105
  '''
95
106
  MATCH (:FuliSpace {id: $space_id, kind: 'personal'})-[:HAS_TASK_CONTEXT_SESSION]->
96
107
  (:FuliTaskContextSession {id: $session_node})-[:HAS_CONTEXT]->(task:FuliTaskContext)
108
+ WHERE ''' + fla_own_work_cypher('task.project_agent_id', 'task.personal_project_id') + '''
97
109
  WITH task ORDER BY task.created_at DESC, task.id LIMIT $limit
98
110
  RETURN task.id AS id, task.token AS token, task.turn_id AS turn_id, task.created_at AS created_at,
99
111
  task.personal_project_id AS project_id, task.project_agent_id AS agent_id,
100
112
  task.record_json AS record_json
101
- ''', space_id=space['id'], limit=MAX_TURNS + 1,
113
+ ''', space_id=space['id'], limit=MAX_TURNS + 1, reader=reader_parameter(reader),
102
114
  session_node=store._task_session_id(space['id'], request.source_application, request.session_id),
103
115
  routing_='r')
104
116
  tasks = []
@@ -136,7 +148,7 @@ async def _turns(store, space, tasks):
136
148
  events = events_by_token.get(task['token'], [])
137
149
  turns.append(SessionTurn(
138
150
  task_id=task['id'], turn_id=task['turn_id'], created_at=task['created_at'],
139
- personal_project_id=task['project_id'],
151
+ personal_project_id=task['project_id'], project_agent_id=task['agent_id'],
140
152
  conversation_id=events[0]['conversation_id'] if events else None,
141
153
  capture_off=task['capture_off'], **_turn_events(events)))
142
154
  return turns, truncated
@@ -186,21 +198,25 @@ def _bounded(text, limit):
186
198
  return text if len(text) <= limit else f'{text[:limit]}…'
187
199
 
188
200
 
189
- async def _session_episodes(store, space, request, tasks):
201
+ async def _session_episodes(store, space, request, tasks, reader):
190
202
  """The episodes the session's checkpoints committed and those that name the
191
203
  session as their source, newest last, each with the turn it belongs to."""
192
204
  task_by_episode = {episode_id: task for task in tasks for episode_id in task['episode_ids']}
193
205
  records, _, _ = await store.runtime.driver.execute_query(
194
206
  '''
195
207
  MATCH (episode:Episodic {group_id: $group_id})
196
- WHERE episode.uuid IN $episode_ids
197
- OR (episode.fuli_session_id = $session_id AND episode.fuli_source_application = $source_application)
208
+ WHERE (episode.uuid IN $episode_ids
209
+ OR (episode.fuli_session_id = $session_id AND episode.fuli_source_application = $source_application
210
+ AND ''' + fla_own_work_cypher('episode.fuli_project_agent_id',
211
+ 'episode.fuli_personal_project_id') + '''))
212
+ AND ''' + fla_episode_visible_cypher('episode') + '''
198
213
  WITH episode ORDER BY episode.created_at DESC, episode.uuid LIMIT $limit
199
214
  RETURN episode.uuid AS id, episode.created_at AS created_at,
200
215
  episode.fuli_personal_project_id AS project_id, episode.fuli_conversation_id AS conversation_id,
201
216
  episode.fuli_source_excerpt AS excerpt
202
217
  ''', group_id=space['group_id'], episode_ids=list(task_by_episode), session_id=request.session_id,
203
- source_application=request.source_application, limit=MAX_EPISODES + 1, routing_='r')
218
+ source_application=request.source_application, limit=MAX_EPISODES + 1, reader=reader_parameter(reader),
219
+ routing_='r')
204
220
  episodes = []
205
221
  for record in reversed(records[:MAX_EPISODES]):
206
222
  created_at = native_datetime(record['created_at'])
@@ -221,7 +237,7 @@ def _task_at(tasks, moment):
221
237
  return started[-1] if started else None
222
238
 
223
239
 
224
- async def _items(store, space, episodes):
240
+ async def _items(store, space, episodes, reader):
225
241
  """What each episode created or updated, and the preferences it only cited
226
242
  again (its words became their evidence). Other items mentioned again
227
243
  changed nothing and are left out. An item is listed once with every
@@ -229,7 +245,11 @@ async def _items(store, space, episodes):
229
245
  turn and project, so a reader allowed fewer projects still finds its own."""
230
246
  items = {}
231
247
  for episode in episodes:
232
- for item_kind, item_id, change in await episode_changes(store, space, [episode['id']]):
248
+ changes = await episode_changes(store, space, [episode['id']])
249
+ hidden = await hidden_refs(store, space, reader, [(item_kind, item_id) for item_kind, item_id, _ in changes])
250
+ for item_kind, item_id, change in changes:
251
+ if (item_kind, item_id) in hidden:
252
+ continue
233
253
  item = items.get((item_kind, item_id))
234
254
  if item is None:
235
255
  if len(items) == MAX_ITEMS:
@@ -237,7 +257,7 @@ async def _items(store, space, episodes):
237
257
  current = await _read_item(store, space, item_id, item_kind)
238
258
  if current is None or (change is None and not current.get('profile_aspect')):
239
259
  continue
240
- _, source_ids = await item_evidence(store, space, item_kind, item_id, limit=0)
260
+ _, source_ids = await item_evidence(store, space, item_kind, item_id, limit=0, reader=reader)
241
261
  summary = await item_summary(store, space, item_kind, item_id, current, source_ids=source_ids)
242
262
  item = items[(item_kind, item_id)] = {'summary': summary, 'sources': []}
243
263
  elif change is None and not item['summary'].profile_aspect:
@@ -12,14 +12,14 @@ from pydantic import Field
12
12
 
13
13
  from .knowledge_item_view_models import KnowledgeItemSummary, KnowledgeScopeProject
14
14
  from .model_base import StrictModel
15
- from .models import SourceApplication
15
+ from .models import AgentReaderRef, SourceApplication
16
16
 
17
17
  # 'evidence': the episode only cited an existing preference again, so its words
18
18
  # became evidence for it without changing it.
19
19
  SessionRecordChange = Literal['created', 'updated', 'evidence']
20
20
 
21
21
 
22
- class SessionRecordsRead(StrictModel):
22
+ class SessionRecordsRead(AgentReaderRef):
23
23
  personal_space_id: str = Field(min_length=1, max_length=128)
24
24
  # None: the link named only the session; its one client is found.
25
25
  source_application: SourceApplication | None = None
@@ -54,6 +54,8 @@ class SessionTurn(StrictModel):
54
54
  turn_id: str | None = None
55
55
  created_at: datetime | None = None
56
56
  personal_project_id: str | None = None
57
+ # The FLA the turn worked under, if any: an Agent reader re-checks it.
58
+ project_agent_id: str | None = None
57
59
  conversation_id: str | None = None
58
60
  # Set when capture was off for this turn's checkpoint.
59
61
  capture_off: SessionCaptureOff | None = None
@@ -118,9 +118,13 @@ class StoreKnowledge:
118
118
  limit: int | None = None,
119
119
  personal_project_id: str | None = None,
120
120
  offset: int | None = None,
121
+ *,
122
+ reader_project_id: str | None = None,
123
+ reader_agent_id: str | None = None,
121
124
  ) -> GraphResult:
122
125
  return await read_graph(
123
- self, actor, space_id, limit, personal_project_id, offset
126
+ self, actor, space_id, limit, personal_project_id, offset,
127
+ reader_project_id=reader_project_id, reader_agent_id=reader_agent_id,
124
128
  )
125
129
 
126
130
  async def collaboration_context(