@tangle-network/agent-app 0.60.28 → 0.60.30

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.
@@ -24,7 +24,45 @@ GIT = STATE / 'home.git'
24
24
  FIXED = {'AGENTS.md', 'SOUL.md', 'IDENTITY.md', 'USER.md', 'MEMORY.md', 'BOOTSTRAP.md'}
25
25
  MAX_FILES = 1024
26
26
  MAX_TOTAL_BYTES = 8 * 1024 * 1024
27
+ MAX_PENDING_BYTES = 1024 * 1024
27
28
  CAPS = {}
29
+ IDENTITY = None
30
+ BINDING_FILE = '.tangle-home-binding.json'
31
+
32
+
33
+ def learning_identity(value):
34
+ if not isinstance(value, dict) or set(value) != {'workspaceId', 'stateId', 'scope'}:
35
+ raise ValueError('invalid home learning identity')
36
+ scope = value['scope']
37
+ if not isinstance(scope, dict):
38
+ raise ValueError('invalid home learning scope')
39
+ kind = scope.get('kind')
40
+ subject = 'memberId' if kind == 'personal' else 'groupId' if kind == 'shared' else None
41
+ if subject is None or set(scope) != {'kind', subject, 'agentId'}:
42
+ raise ValueError('invalid home learning scope')
43
+ for field in [value['workspaceId'], value['stateId'], scope[subject], scope['agentId']]:
44
+ if not isinstance(field, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:-]{0,127}', field):
45
+ raise ValueError('invalid home learning identity field')
46
+ return value
47
+
48
+
49
+ def load_identity(policy):
50
+ # The expected identity is operator-owned configuration outside the volume.
51
+ # Both home and journal carry it, so mixing two restored directories fails
52
+ # closed even when st_dev happens to match. No request can change identity.
53
+ identity = policy.get('identity')
54
+ if identity is not None:
55
+ learning_identity(identity)
56
+ for directory in [ROOT, STATE]:
57
+ marker = directory / BINDING_FILE
58
+ if marker.exists() or marker.is_symlink():
59
+ protected(marker)
60
+ actual = learning_identity(json.loads(marker.read_text(encoding='utf8')))
61
+ if actual != identity:
62
+ raise ValueError('home learning identity does not match the installed volume')
63
+ elif identity is not None:
64
+ raise ValueError('home learning identity marker is missing')
65
+ return identity
28
66
 
29
67
 
30
68
  def protected(path, directory=False):
@@ -40,6 +78,7 @@ def protected(path, directory=False):
40
78
 
41
79
 
42
80
  def load_policy():
81
+ global IDENTITY
43
82
  if os.geteuid() != 0 or len(sys.argv) != 1:
44
83
  raise ValueError('use the installed privileged home command without arguments')
45
84
  for path in [pathlib.Path('/etc'), CONFIG.parent, pathlib.Path('/var'),
@@ -49,6 +88,7 @@ def load_policy():
49
88
  raise ValueError('home and journal must share one persistent filesystem')
50
89
  protected(CONFIG)
51
90
  policy = json.loads(CONFIG.read_text(encoding='utf8'))
91
+ IDENTITY = load_identity(policy)
52
92
  uid = policy.get('runtimeUid')
53
93
  if not isinstance(uid, int) or isinstance(uid, bool) or uid <= 0:
54
94
  raise ValueError('home runtime identity is invalid')
@@ -107,7 +147,8 @@ def read(name):
107
147
  return ''
108
148
  if path.stat().st_size > cap(name) * 4:
109
149
  raise ValueError('home byte budget exceeded')
110
- return bounded(name, path.read_text(encoding='utf8'))
150
+ with path.open('r', encoding='utf8', newline='') as content:
151
+ return bounded(name, content.read())
111
152
 
112
153
 
113
154
  def paths():
@@ -117,6 +158,9 @@ def paths():
117
158
  protected(pathlib.Path(directory) / child, True)
118
159
  for child in files:
119
160
  name = str((pathlib.Path(directory) / child).relative_to(ROOT))
161
+ if name == BINDING_FILE:
162
+ protected(ROOT / name)
163
+ continue
120
164
  checked(name)
121
165
  result.append(name)
122
166
  if len(result) > MAX_FILES:
@@ -124,37 +168,42 @@ def paths():
124
168
  return sorted(result)
125
169
 
126
170
 
171
+ def sync_directory(path):
172
+ directory = os.open(path, os.O_DIRECTORY)
173
+ try:
174
+ os.fsync(directory)
175
+ finally:
176
+ os.close(directory)
177
+
178
+
127
179
  def atomic(path, content, mode=0o444):
128
180
  fd, temporary = tempfile.mkstemp(prefix='.home-', dir=STATE)
129
181
  try:
130
- with os.fdopen(fd, 'w', encoding='utf8') as output:
182
+ with os.fdopen(fd, 'w', encoding='utf8', newline='') as output:
131
183
  output.write(content)
132
184
  output.flush()
133
185
  os.fchmod(output.fileno(), mode)
134
186
  os.fsync(output.fileno())
135
187
  os.replace(temporary, path)
136
- directory = os.open(path.parent, os.O_DIRECTORY)
137
- try:
138
- os.fsync(directory)
139
- finally:
140
- os.close(directory)
188
+ sync_directory(path.parent)
141
189
  finally:
142
190
  if os.path.exists(temporary):
143
191
  os.unlink(temporary)
144
192
 
145
193
 
146
- def git(*args):
194
+ def git(*args, trim=True):
147
195
  # Neither the caller's PATH/HOME nor git-related environment is inherited.
148
196
  env = {'PATH': '/usr/bin:/bin', 'HOME': '/nonexistent', 'LANG': 'C.UTF-8',
149
197
  'GIT_CONFIG_NOSYSTEM': '1', 'GIT_CONFIG_GLOBAL': '/dev/null', 'GIT_TERMINAL_PROMPT': '0'}
150
198
  result = subprocess.run(['/usr/bin/git', '--git-dir=' + str(GIT), '--work-tree=' + str(ROOT),
151
199
  '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'core.fsync=all',
152
200
  '-c', 'user.name=Tangle home', '-c', 'user.email=home@localhost', *args],
153
- cwd=ROOT, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
201
+ cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
154
202
  timeout=20, check=False)
155
203
  if result.returncode:
156
204
  raise RuntimeError('home git operation failed')
157
- return result.stdout.strip()
205
+ output = result.stdout.decode('utf8')
206
+ return output.strip() if trim else output
158
207
 
159
208
 
160
209
  def checkpoint():
@@ -173,10 +222,22 @@ def checkpoint():
173
222
  return {'commit': git('rev-parse', '--verify', 'HEAD'), 'changed': changed}
174
223
 
175
224
 
225
+ def validate_updates(updates):
226
+ if not isinstance(updates, dict) or not updates or len(updates) > MAX_FILES:
227
+ raise ValueError('home updates must be a nonempty bounded object')
228
+ for name, value in updates.items():
229
+ checked(name)
230
+ if name == 'AGENTS.md':
231
+ raise ValueError('AGENTS.md is platform-owned')
232
+ if value is not None:
233
+ bounded(name, value)
234
+
235
+
176
236
  def apply(updates):
177
237
  # Validate the whole change before writing any document. A durable journal
178
238
  # finishes the same transaction after a crash instead of mixing two nightly
179
239
  # summaries. Neither the journal nor the git metadata is agent-writable.
240
+ validate_updates(updates)
180
241
  current = {name: read(name) for name in paths()}
181
242
  for name, value in updates.items():
182
243
  checked(name)
@@ -196,8 +257,12 @@ def finish_pending():
196
257
  pending = STATE / 'pending.json'
197
258
  if not pending.exists():
198
259
  return None
199
- protected(pending)
260
+ if protected(pending).st_size > MAX_PENDING_BYTES:
261
+ raise ValueError('home pending journal exceeds its byte budget')
200
262
  updates = json.loads(pending.read_text(encoding='utf8'))
263
+ # Even a corrupt operator-restored journal must be rejected in full before
264
+ # recovery touches a document. Valid journals were budgeted before staging.
265
+ validate_updates(updates)
201
266
  for name, content in updates.items():
202
267
  target = checked(name)
203
268
  if name == 'AGENTS.md':
@@ -205,6 +270,7 @@ def finish_pending():
205
270
  if content is None:
206
271
  if target.exists():
207
272
  target.unlink()
273
+ sync_directory(target.parent)
208
274
  else:
209
275
  bounded(name, content)
210
276
  parent = ROOT
@@ -213,14 +279,84 @@ def finish_pending():
213
279
  if not parent.exists():
214
280
  parent.mkdir(mode=0o755)
215
281
  parent.chmod(0o755)
282
+ sync_directory(parent.parent)
216
283
  protected(parent, True)
217
284
  checked(name)
218
285
  atomic(target, content)
219
286
  result = checkpoint()
220
287
  pending.unlink()
288
+ sync_directory(STATE)
221
289
  return result
222
290
 
223
291
 
292
+ def portable(name):
293
+ checked(name)
294
+ if name not in {'USER.md', 'MEMORY.md'} and not name.startswith(('memory/', 'skills/')):
295
+ raise ValueError('path is outside portable learning state')
296
+ return name
297
+
298
+
299
+ def snapshot_base(since, head):
300
+ if not isinstance(since, str) or not re.fullmatch(r'(?:[a-f0-9]{40}|[a-f0-9]{64})', since):
301
+ raise ValueError('snapshot since must be an exact base commit')
302
+ try:
303
+ if git('cat-file', '-t', since) != 'commit':
304
+ raise ValueError('snapshot since must be a commit')
305
+ git('merge-base', '--is-ancestor', since, head)
306
+ except RuntimeError:
307
+ raise ValueError('snapshot base commit is missing or is not an ancestor of the current home') from None
308
+ return since
309
+
310
+
311
+ def deleted_portable_paths(since, head):
312
+ # Git already records removals. Retain absent paths as tombstones so an
313
+ # older imported snapshot cannot silently recreate them. The range belongs
314
+ # to an immutable turn pin, never all lifetime history. Disable rename
315
+ # detection: a moved skill still deleted its old portable path.
316
+ deleted = set(filter(None, git('log', '--format=', '--name-only', '--diff-filter=D',
317
+ '--no-renames', '-z', since + '..' + head).split('\0')))
318
+ result = set()
319
+ for name in deleted:
320
+ checked(name)
321
+ if name in {'USER.md', 'MEMORY.md'} or name.startswith(('memory/', 'skills/')):
322
+ result.add(name)
323
+ if len(result) > MAX_FILES:
324
+ raise ValueError('portable home history exceeds the snapshot file-count budget')
325
+ return result
326
+
327
+
328
+ def portable_inventory(since, head):
329
+ existing = set(paths())
330
+ names = {name for name in existing | deleted_portable_paths(since, head)
331
+ if name in {'USER.md', 'MEMORY.md'} or name.startswith(('memory/', 'skills/'))}
332
+ if len(names) > MAX_FILES:
333
+ raise ValueError('portable home history exceeds the snapshot file-count budget')
334
+ return existing, names
335
+
336
+
337
+ def portable_snapshot(commit, since):
338
+ existing, names = portable_inventory(since, commit)
339
+ files = [{'path': name, 'content': git('show', commit + ':' + name, trim=False)
340
+ if name in existing else None} for name in sorted(names)]
341
+ if sum(len((file['content'] or '').encode('utf8')) for file in files) > MAX_TOTAL_BYTES:
342
+ raise ValueError('home total-byte budget exceeded')
343
+ return {'commit': commit, 'since': since, 'files': files}
344
+
345
+
346
+ def expect_head(request):
347
+ expected = request.get('expectedHead')
348
+ if not isinstance(expected, str) or not re.fullmatch(r'(?:[a-f0-9]{40}|[a-f0-9]{64})', expected):
349
+ raise ValueError('expectedHead is required; read the current home commit before replacing or deleting files')
350
+ if expected != git('rev-parse', '--verify', 'HEAD'):
351
+ raise ValueError('home changed; reread the current snapshot before retrying')
352
+
353
+
354
+ def receipt(result):
355
+ # A local fsynced Git checkpoint is not evidence of remote persistence or a
356
+ # successful sandbox-volume restore. The host must attest those separately.
357
+ return {**result, 'identity': IDENTITY, 'checkpointScope': 'local'}
358
+
359
+
224
360
  def main():
225
361
  load_policy()
226
362
  os.umask(0o077)
@@ -228,13 +364,18 @@ def main():
228
364
  if len(raw) > 262144:
229
365
  raise ValueError('home command input exceeds 262144 bytes')
230
366
  request = json.loads(raw)
231
- fields = {'status': set(), 'commit': set(), 'bootstrap': set(), 'read': {'path'},
232
- 'write': {'path', 'content'}, 'append': {'path', 'content'}, 'delete': {'path'},
367
+ fields = {'status': set(), 'snapshot': set(), 'commit': set(), 'bootstrap': set(), 'read': {'path'},
368
+ 'write': {'path', 'content', 'expectedHead'}, 'append': {'path', 'content'},
369
+ 'delete': {'path', 'expectedHead'}, 'reconcile': {'updates', 'expectedHead'},
233
370
  'consolidate': {'user', 'memory', 'expectedHead'}}
234
371
  if not isinstance(request, dict) or request.get('action') not in fields:
235
372
  raise ValueError('unknown home operation')
236
373
  action = request['action']
237
- if set(request) != {'action'} | fields[action]:
374
+ if action in {'write', 'delete', 'reconcile', 'consolidate'} and 'expectedHead' not in request:
375
+ raise ValueError('expectedHead is required; read the current home commit before replacing or deleting files')
376
+ required = {'action'} | fields[action]
377
+ optional = {'since'} if action in {'snapshot', 'reconcile'} else set()
378
+ if not required <= set(request) or not set(request) <= required | optional:
238
379
  raise ValueError('invalid home operation fields')
239
380
  lock = STATE / 'home.lock'
240
381
  with lock.open('a') as handle:
@@ -244,29 +385,56 @@ def main():
244
385
  git('init')
245
386
  protected(GIT, True)
246
387
  finish_pending()
388
+ if action == 'snapshot':
389
+ if 'since' in request:
390
+ snapshot_base(request['since'], git('rev-parse', '--verify', 'HEAD'))
391
+ # Reconcile any operator-updated seed before naming a revision;
392
+ # export the committed bytes, not an uncheckpointed filesystem view.
393
+ current_commit = checkpoint()['commit']
394
+ return receipt(portable_snapshot(current_commit, request.get('since', current_commit)))
247
395
  if action == 'read':
248
- return {'path': request['path'], 'content': read(request['path']),
249
- 'commit': git('rev-parse', '--verify', 'HEAD')}
396
+ return receipt({'path': request['path'], 'content': read(request['path']),
397
+ 'commit': git('rev-parse', '--verify', 'HEAD')})
250
398
  if action in {'write', 'append', 'delete'}:
399
+ if action != 'append':
400
+ expect_head(request)
251
401
  name = request['path']
252
402
  content = None if action == 'delete' else request['content']
403
+ if action != 'delete' and not isinstance(content, str):
404
+ raise ValueError('home content must be text')
253
405
  if action == 'append':
254
406
  content = read(name) + content
255
407
  result = apply({name: content})
256
- return {**result, 'path': name, 'ownerNoticeRequired': name == 'SOUL.md'}
408
+ return receipt({**result, 'path': name, 'ownerNoticeRequired': name == 'SOUL.md'})
409
+ if action == 'reconcile':
410
+ expect_head(request)
411
+ since = snapshot_base(request.get('since', request['expectedHead']), request['expectedHead'])
412
+ updates = request['updates']
413
+ if not isinstance(updates, dict):
414
+ raise ValueError('home updates must be a nonempty bounded object')
415
+ for name in updates:
416
+ portable(name)
417
+ _existing, names = portable_inventory(since, request['expectedHead'])
418
+ if len(names | set(updates)) > MAX_FILES:
419
+ raise ValueError('portable home history exceeds the snapshot file-count budget')
420
+ for name, value in updates.items():
421
+ if value is None and name not in names:
422
+ raise ValueError('cannot persist deletion of a never-tracked portable path in this snapshot range')
423
+ result = apply(updates)
424
+ return receipt({**result, **portable_snapshot(result['commit'], since)})
257
425
  if action == 'bootstrap':
258
426
  if not read('IDENTITY.md').strip():
259
427
  raise ValueError('fill IDENTITY.md before completing bootstrap')
260
- return apply({'BOOTSTRAP.md': None})
428
+ return receipt(apply({'BOOTSTRAP.md': None}))
261
429
  if action == 'consolidate':
262
- if request['expectedHead'] != git('rev-parse', '--verify', 'HEAD'):
263
- raise ValueError('home changed; reread notes before consolidating')
264
- return apply({'USER.md': request['user'], 'MEMORY.md': request['memory']})
430
+ expect_head(request)
431
+ return receipt(apply({'USER.md': bounded('USER.md', request['user']),
432
+ 'MEMORY.md': bounded('MEMORY.md', request['memory'])}))
265
433
  result = checkpoint()
266
434
  if action == 'status':
267
435
  result['files'] = [{'path': name, 'characters': len(read(name)),
268
436
  'sha256': hashlib.sha256(read(name).encode('utf8')).hexdigest()} for name in paths()]
269
- return result
437
+ return receipt(result)
270
438
 
271
439
 
272
440
  if __name__ == '__main__':
@@ -9,9 +9,26 @@ const BASE = '/var/lib/tangle-agent'
9
9
  const STATE = `${BASE}/state`
10
10
  const CONFIG = '/etc/tangle-agent/home.json'
11
11
  const HELPER = '/usr/local/libexec/tangle-agent-home.py'
12
+ const BINDING_FILE = '.tangle-home-binding.json'
12
13
  const run = promisify(execFile)
13
14
  const cleanEnv = { PATH: '/usr/bin:/bin', LANG: 'C.UTF-8' }
14
15
 
16
+ /** Identity comes only from trusted operator setup, never model arguments. */
17
+ export function validateHomeIdentity(value) {
18
+ const record = (input, keys) => input !== null && typeof input === 'object' && !Array.isArray(input) &&
19
+ Object.keys(input).length === keys.length && keys.every(key => Object.hasOwn(input, key))
20
+ if (!record(value, ['workspaceId', 'stateId', 'scope'])) throw new Error('Invalid home learning identity')
21
+ const scope = value.scope
22
+ const subject = scope?.kind === 'personal' ? 'memberId' : scope?.kind === 'shared' ? 'groupId' : undefined
23
+ if (!subject || !record(scope, ['kind', subject, 'agentId'])) throw new Error('Invalid home learning scope')
24
+ if (![value.workspaceId, value.stateId, scope[subject], scope.agentId].every(field =>
25
+ typeof field === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(field))) {
26
+ throw new Error('Invalid home learning identity field')
27
+ }
28
+ return { workspaceId: value.workspaceId, stateId: value.stateId,
29
+ scope: { kind: scope.kind, [subject]: scope[subject], agentId: scope.agentId } }
30
+ }
31
+
15
32
  async function protectedEntry(path, directory = false) {
16
33
  const info = await lstat(path)
17
34
  if (info.uid !== 0 || (info.mode & 0o022) || info.isSymbolicLink() ||
@@ -26,6 +43,9 @@ export async function homeOperation(request, signal) {
26
43
  signal?.throwIfAborted()
27
44
  const input = JSON.stringify(request)
28
45
  if (Buffer.byteLength(input) > 262144) throw new Error('Home request is too large')
46
+ // At most 8 MiB of portable text; JSON control-character escaping can expand
47
+ // it sixfold. Ordinary single-file/status receipts retain their smaller cap.
48
+ const maxOutput = ['snapshot', 'reconcile'].includes(request.action) ? 64 * 1024 * 1024 : 1024 * 1024
29
49
  await protectedEntry(HELPER)
30
50
  return new Promise((resolve, reject) => {
31
51
  const child = spawn('/usr/bin/sudo', ['-n', '--', '/usr/bin/python3', '-I', HELPER], {
@@ -40,8 +60,8 @@ export async function homeOperation(request, signal) {
40
60
  signal?.addEventListener('abort', stop, { once: true })
41
61
  child.stdout.on('data', bytes => {
42
62
  size += Buffer.byteLength(bytes)
43
- if (size > 1024 * 1024) stop()
44
- else output += bytes.toString('utf8')
63
+ if (size > maxOutput) stop()
64
+ else output += bytes
45
65
  })
46
66
  child.stderr.on('data', bytes => { if (errorOutput.length < 2048) errorOutput += bytes.toString('utf8') })
47
67
  child.stdin.on('error', () => { inputFailed = true })
@@ -50,7 +70,7 @@ export async function homeOperation(request, signal) {
50
70
  clearTimeout(timer)
51
71
  signal?.removeEventListener('abort', stop)
52
72
  if (signal?.aborted) return reject(signal.reason)
53
- if (code !== 0 || killed || inputFailed || timedOut || size > 1024 * 1024) {
73
+ if (code !== 0 || killed || inputFailed || timedOut || size > maxOutput) {
54
74
  let detail = 'Home operation failed or is unconfirmed; inspect home_status before retrying a write'
55
75
  try { const value = JSON.parse(errorOutput); if (typeof value.error === 'string') detail = value.error }
56
76
  catch { detail = 'Protected home returned no validation receipt; inspect home_status before retrying a write' }
@@ -91,10 +111,11 @@ export async function checkpointHome(directoryName, signal) {
91
111
  }
92
112
 
93
113
  /** Image/operator install only. Uses the same canonical profile seed records. */
94
- export async function installProtectedHome(runtimeUser) {
114
+ export async function installProtectedHome(runtimeUser, learningIdentity = null) {
95
115
  if (process.getuid?.() !== 0 || !/^[a-z_][a-z0-9_-]{0,31}$/.test(runtimeUser ?? '')) {
96
116
  throw new Error('install-home requires root and an explicit non-root runtime user')
97
117
  }
118
+ const identity = learningIdentity === null ? null : validateHomeIdentity(learningIdentity)
98
119
  const uid = Number((await run('/usr/bin/id', ['-u', runtimeUser])).stdout.trim())
99
120
  const gid = Number((await run('/usr/bin/id', ['-g', runtimeUser])).stdout.trim())
100
121
  if (!Number.isSafeInteger(uid) || uid <= 0 || !Number.isSafeInteger(gid) || gid < 0) throw new Error('Invalid runtime UID/GID')
@@ -104,6 +125,26 @@ export async function installProtectedHome(runtimeUser) {
104
125
  await protectedEntry(directory, true)
105
126
  }
106
127
  if ((await lstat(STATE)).dev !== (await lstat(PROTECTED_HOME)).dev) throw new Error('Home and journal must share one persistent filesystem')
128
+ // Preflight both immutable volume markers before changing any seed/config.
129
+ // Reinstalling a bound home requires the same explicit operator identity.
130
+ let markers = 0
131
+ for (const directory of [PROTECTED_HOME, STATE]) {
132
+ const marker = `${directory}/${BINDING_FILE}`
133
+ try {
134
+ await protectedEntry(marker)
135
+ const existing = validateHomeIdentity(JSON.parse(await readFile(marker, 'utf8')))
136
+ if (JSON.stringify(existing) !== JSON.stringify(identity)) throw new Error('Home learning identity does not match the installed volume')
137
+ markers++
138
+ } catch (error) { if (error.code !== 'ENOENT') throw error }
139
+ }
140
+ if (markers === 1) throw new Error('Home and journal learning identity markers must be restored together')
141
+ try {
142
+ await protectedEntry(CONFIG)
143
+ const previous = JSON.parse(await readFile(CONFIG, 'utf8')).identity
144
+ if (previous != null && (markers !== 2 || JSON.stringify(validateHomeIdentity(previous)) !== JSON.stringify(identity))) {
145
+ throw new Error('Cannot replace an existing home learning identity')
146
+ }
147
+ } catch (error) { if (error.code !== 'ENOENT') throw error }
107
148
  async function replace(path, body, mode) {
108
149
  const temporary = join(dirname(path), `.tangle-${randomUUID()}`)
109
150
  const file = await open(temporary, 'wx', mode)
@@ -111,6 +152,8 @@ export async function installProtectedHome(runtimeUser) {
111
152
  await file.writeFile(body)
112
153
  await file.sync()
113
154
  await rename(temporary, path)
155
+ const directory = await open(dirname(path), 'r')
156
+ try { await directory.sync() } finally { await directory.close() }
114
157
  } finally {
115
158
  await file.close()
116
159
  try { await unlink(temporary) } catch (error) { if (error.code !== 'ENOENT') throw error }
@@ -133,7 +176,10 @@ export async function installProtectedHome(runtimeUser) {
133
176
  } catch (error) { if (error.code !== 'ENOENT') throw error }
134
177
  await replace(path, mount.resource.content, 0o444)
135
178
  }
136
- await replace(CONFIG, JSON.stringify({ runtimeUid: uid, caps: DEFAULT_HOME_LIMITS,
179
+ if (identity) for (const directory of [PROTECTED_HOME, STATE]) {
180
+ await replace(`${directory}/${BINDING_FILE}`, JSON.stringify(identity), directory === STATE ? 0o400 : 0o444)
181
+ }
182
+ await replace(CONFIG, JSON.stringify({ runtimeUid: uid, caps: DEFAULT_HOME_LIMITS, identity,
137
183
  agentsSha256: createHash('sha256').update(agents).digest('hex') }), 0o444)
138
184
  await replace(HELPER, await readFile(new URL('./home-maintenance.py', import.meta.url)), 0o444)
139
185
  // Verify inherited sudoers ordering rather than silently leaving a broad grant.
@@ -162,5 +208,5 @@ export async function installProtectedHome(runtimeUser) {
162
208
  })
163
209
  if (!status.commit) throw new Error('Protected home has no Git checkpoint')
164
210
  await replace(`${STATE}/initialized`, 'tangle-agent-home-v2\n', 0o400)
165
- return { home: PROTECTED_HOME, runtimeUid: uid, commit: status.commit }
211
+ return { home: PROTECTED_HOME, runtimeUid: uid, commit: status.commit, identity, checkpointScope: 'local' }
166
212
  }
@@ -72,8 +72,8 @@ export function buildGeneralAgent(configInput) {
72
72
  const substrate = agentProfileSchema.parse({
73
73
  name: 'tangle-agent-v1', model: { default: config.model },
74
74
  prompt: { systemPrompt: GENERAL_AGENT_SYSTEM_PROMPT, instructions: [
75
- `Your durable home is ${config.home}. It is preinstalled and root-owned. Read AGENTS.md and SOUL.md there. Use home_read, home_write, home_append, home_status, home_bootstrap and home_consolidate. Ordinary shell and code remain available outside this protected directory. Never create an unprotected replacement home.`,
76
- 'The protected writer enforces Unicode-character, byte and file-count caps before any memory mutation. Every successful mutation returns a Git commit. A SOUL.md change requires an immediate owner notice. Keep credentials and third-party private data out of memory.',
75
+ `Your protected home is ${config.home}. It is preinstalled and root-owned. Read AGENTS.md and SOUL.md there. Use home_read, home_write, home_append, home_status, home_bootstrap and home_consolidate. Ordinary shell and code remain available outside this protected directory. Never create an unprotected replacement home.`,
76
+ 'The protected writer enforces Unicode-character, byte and file-count caps before any memory mutation. Replacements, deletions and consolidation require expectedHead from the snapshot you read. Reread after a conflict or an unconfirmed append. Every successful mutation returns a local Git checkpoint, not proof of remote persistence. A SOUL.md change requires an immediate owner notice. Keep credentials and third-party private data out of memory.',
77
77
  'Use the published tangle_agent tools for Router search/read, Browser Agent and image/video generation. Use native computer-use tools for the virtual display and explicitly mounted Hub connections for email, calendar and ph0ny. Do not substitute direct provider APIs or disable the allowlist proxy.',
78
78
  'The platform scheduler owns reminders and maintenance. The hourly heartbeat and nightly consolidation use the same consenting owner session. A queued workflow is not a completed reminder; report the actual workflow and eventual line receipts.',
79
79
  ] },
@@ -130,20 +130,21 @@ export async function serve() {
130
130
  // The root-owned writer validates the same JSON again before each mutation.
131
131
  const homePath = z.string().min(1).max(100)
132
132
  const homeContent = z.string().max(64000)
133
+ const homeHead = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)
133
134
  tool('home_status', 'Read the protected home file inventory and current Git commit. No file contents are included.',
134
135
  z.object({}).strict(), (_args, signal) => homeOperation({ action: 'status' }, signal))
135
- tool('home_read', 'Read one protected home document. Use this for current memory and the commit needed by home_consolidate.',
136
+ tool('home_read', 'Read one protected home document. Use the returned commit as expectedHead for a replacement, deletion or consolidation. Reread after a conflict.',
136
137
  z.object({ path: homePath }).strict(), (args, signal) => homeOperation({ action: 'read', ...args }, signal))
137
- tool('home_write', 'Write bounded personal memory or a skill and commit it. AGENTS.md is immutable. Tell the owner immediately when ownerNoticeRequired is returned for a SOUL.md change.',
138
- z.object({ path: homePath, content: homeContent }).strict(), (args, signal) => homeOperation({ action: 'write', ...args }, signal))
139
- tool('home_append', 'Append a bounded daily note or preference and commit it. Never store credentials or private third-party records.',
138
+ tool('home_write', 'Replace bounded personal memory or a skill using expectedHead from the document you read. A concurrent change requires rereading. AGENTS.md is immutable. Tell the owner immediately when ownerNoticeRequired is returned for a SOUL.md change.',
139
+ z.object({ path: homePath, content: homeContent, expectedHead: homeHead }).strict(), (args, signal) => homeOperation({ action: 'write', ...args }, signal))
140
+ tool('home_append', 'Atomically append a bounded daily note or preference and commit it. Read after an unconfirmed result before retrying: append is not idempotent. Never store credentials or private third-party records.',
140
141
  z.object({ path: homePath, content: homeContent }).strict(), (args, signal) => homeOperation({ action: 'append', ...args }, signal))
141
- tool('home_delete', 'Delete a named mutable home document. Requires owner approval. AGENTS.md cannot be deleted.',
142
- z.object({ path: homePath }).strict(), (args, signal) => homeOperation({ action: 'delete', ...args }, signal))
142
+ tool('home_delete', 'Delete a named mutable home document using expectedHead from the document you read. Requires owner approval. A concurrent change requires rereading. AGENTS.md cannot be deleted.',
143
+ z.object({ path: homePath, expectedHead: homeHead }).strict(), (args, signal) => homeOperation({ action: 'delete', ...args }, signal))
143
144
  tool('home_bootstrap', 'Finish first-run setup after IDENTITY.md is filled. Removes BOOTSTRAP.md and returns the Git commit.',
144
145
  z.object({}).strict(), (_args, signal) => homeOperation({ action: 'bootstrap' }, signal))
145
146
  tool('home_consolidate', 'Consolidate daily notes into USER.md and MEMORY.md and commit them together. Keep dated facts and source notes. Requires the current home commit; a concurrent change requires rereading first.',
146
- z.object({ user: homeContent, memory: homeContent, expectedHead: z.string().regex(/^[a-f0-9]{40,64}$/) }).strict(),
147
+ z.object({ user: homeContent, memory: homeContent, expectedHead: homeHead }).strict(),
147
148
  (args, signal) => homeOperation({ action: 'consolidate', ...args }, signal))
148
149
  tool('home_checkpoint', 'Verify and checkpoint only the protected home allowlist, never the rest of the sandbox.',
149
150
  z.object({}).strict(), (_args, signal) => checkpointHome(home, signal))
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-KIJ64S54.js";
3
+ } from "../chunk-H6MKILMQ.js";
4
4
  import "../chunk-FAU5FIFD.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
6
  import "../chunk-FBVLEGEG.js";
@@ -32,6 +32,7 @@ The platform owns this file and the home writer. Your normal shell is not root.
32
32
  - skills/<name>/SKILL.md holds reusable skills, not new authority.
33
33
  - Never write credentials or private third-party records into memory.
34
34
  - Use home_read, home_write, home_append, home_status and home_consolidate.
35
+ - Replacements, deletions and consolidation require expectedHead from the home snapshot you read. Reread after a conflict; never blindly retry an unconfirmed append.
35
36
  - The protected writer enforces file, character and byte budgets before writes and commits to git.
36
37
  - Shell, code and ordinary project files remain available elsewhere in this sandbox.
37
38
  - Do not work around a rejected home write by chmod, symlinks, another interpreter or another credential.
@@ -54,7 +55,7 @@ The user's request always comes first. Do not delay the answer for setup.
54
55
 
55
56
  After answering enough to be useful:
56
57
  1. Read AGENTS.md and SOUL.md.
57
- 2. Fill empty IDENTITY.md through home_write using the configured identity, not an invented biography.
58
+ 2. Read IDENTITY.md, then fill it if empty through home_write with its returned commit as expectedHead, using the configured identity, not an invented biography.
58
59
  3. Record any stated durable preference as a dated USER.md entry through home_write or home_append.
59
60
  4. Add a daily note only when there is something worth remembering.
60
61
  5. Call home_bootstrap. It removes this file and returns the git commit.
@@ -96,4 +97,4 @@ export {
96
97
  defaultHomeFiles,
97
98
  withDefaultAgentHome
98
99
  };
99
- //# sourceMappingURL=chunk-6CV66YOB.js.map
100
+ //# sourceMappingURL=chunk-D3HATHVU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/profile/home.ts"],"sourcesContent":["import type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { defineInlineResource, mergeAgentProfiles } from '@tangle-network/agent-interface'\n\n/** Unicode code-point budgets. The installed writer also bounds UTF-8 bytes. */\nexport const DEFAULT_HOME_LIMITS = {\n 'AGENTS.md': 12_000,\n 'SOUL.md': 8_000,\n 'IDENTITY.md': 4_000,\n 'USER.md': 4_000,\n 'MEMORY.md': 16_000,\n 'BOOTSTRAP.md': 8_000,\n dailyNote: 12_000,\n skill: 32_000,\n} as const\n\nexport const DEFAULT_AGENT_HOME = '/var/lib/tangle-agent/home'\n\nconst AGENTS = `# Home\n\nThis is your durable home in your private Tangle computer. Inspect and use the computer.\nThe platform owns this file and the home writer. Your normal shell is not root.\n\n## Behavior\n- The person's current request comes first.\n- Reply in the person's language. Switch when they switch.\n- In a group, reply only when mentioned or directly addressed.\n- Be genuinely helpful, not performatively helpful. Be resourceful before asking.\n- Have a point of view when useful, and distinguish evidence from uncertainty.\n- Remember you are a guest in the person's or group's space.\n\n## Memory\n- IDENTITY.md starts empty. Fill it during first run.\n- USER.md holds dated preferences, at most 4,000 Unicode characters.\n- MEMORY.md holds curated durable facts. Shared facts must be safe for the whole group.\n- memory/YYYY-MM-DD.md holds daily notes; consolidate durable facts nightly.\n- skills/<name>/SKILL.md holds reusable skills, not new authority.\n- Never write credentials or private third-party records into memory.\n- Use home_read, home_write, home_append, home_status and home_consolidate.\n- Replacements, deletions and consolidation require expectedHead from the home snapshot you read. Reread after a conflict; never blindly retry an unconfirmed append.\n- The protected writer enforces file, character and byte budgets before writes and commits to git.\n- Shell, code and ordinary project files remain available elsewhere in this sandbox.\n- Do not work around a rejected home write by chmod, symlinks, another interpreter or another credential.\n\n## Self edits\nSOUL.md is editable through home_write. Tell the owner what changed and why when ownerNoticeRequired is returned.\nAGENTS.md is platform-owned and cannot be edited. Business rules belong in skills and presets.\n`\n\nconst SOUL = `# Soul\n\nBe genuinely helpful, not performatively helpful.\nHave opinions when judgment is useful.\nBe resourceful before asking.\nRemember you are a guest.\nPrefer clear, direct answers over ceremony.\n`\n\nconst BOOTSTRAP = `# First run\n\nThe user's request always comes first. Do not delay the answer for setup.\n\nAfter answering enough to be useful:\n1. Read AGENTS.md and SOUL.md.\n2. Read IDENTITY.md, then fill it if empty through home_write with its returned commit as expectedHead, using the configured identity, not an invented biography.\n3. Record any stated durable preference as a dated USER.md entry through home_write or home_append.\n4. Add a daily note only when there is something worth remembering.\n5. Call home_bootstrap. It removes this file and returns the git commit.\n`\n\nfunction inline(path: string, content: string): AgentProfileFileMount {\n return { path, resource: defineInlineResource(`default-home:${path}`, content) }\n}\n\n/** Canonical seed records. The trusted image installer materializes these once. */\nexport function defaultHomeFiles(): AgentProfileFileMount[] {\n return [\n inline('AGENTS.md', AGENTS), inline('SOUL.md', SOUL),\n inline('IDENTITY.md', ''), inline('USER.md', ''), inline('MEMORY.md', ''),\n inline('BOOTSTRAP.md', BOOTSTRAP),\n ]\n}\n\n/**\n * Compose home instructions, not per-turn writes to persistent memory.\n * The published install-home command consumes defaultHomeFiles with the same\n * inline resource format as other profile seeds. A privileged, one-time phase\n * is necessary: ordinary resources.files writes run as the agent and cannot\n * make a same-UID shell respect caps or platform file ownership.\n */\nexport function withDefaultAgentHome(profile: AgentProfile): AgentProfile {\n const reserved = new Set(['AGENTS.md', 'SOUL.md', 'IDENTITY.md', 'USER.md', 'MEMORY.md', 'BOOTSTRAP.md', '.tangle/home.py'])\n for (const file of profile.resources?.files ?? []) {\n const parts = file.path.replace(/\\\\/g, '/').split('/').filter(part => part && part !== '.')\n if (parts.includes('..')) throw new Error('Home-aware profiles require canonical file mount paths')\n const path = parts.join('/')\n if (reserved.has(path) || path === 'var/lib/tangle-agent' || path.startsWith('var/lib/tangle-agent/') ||\n path.startsWith('etc/tangle-agent/') || path === 'usr/local/libexec/tangle-agent-home.py') {\n throw new Error('Do not remount the protected home; use the home tools and business skills')\n }\n }\n const merged = mergeAgentProfiles(profile, { prompt: { instructions: [\n `Your git-tracked home is ${DEFAULT_AGENT_HOME}. Read AGENTS.md and SOUL.md there.`,\n 'Use the protected home tools for memory and bootstrap. Native shell remains available for ordinary code and project files. A missing protected-home installation is an infrastructure error, not permission to create an unprotected replacement.',\n ] } })\n if (!merged) throw new Error('Home profile composition returned no profile')\n return merged\n}\n"],"mappings":";AACA,SAAS,sBAAsB,0BAA0B;AAGlD,IAAM,sBAAsB;AAAA,EACjC,aAAa;AAAA,EACb,WAAW;AAAA,EACX,eAAe;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,OAAO;AACT;AAEO,IAAM,qBAAqB;AAElC,IAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+Bf,IAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASb,IAAM,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYlB,SAAS,OAAO,MAAc,SAAwC;AACpE,SAAO,EAAE,MAAM,UAAU,qBAAqB,gBAAgB,IAAI,IAAI,OAAO,EAAE;AACjF;AAGO,SAAS,mBAA4C;AAC1D,SAAO;AAAA,IACL,OAAO,aAAa,MAAM;AAAA,IAAG,OAAO,WAAW,IAAI;AAAA,IACnD,OAAO,eAAe,EAAE;AAAA,IAAG,OAAO,WAAW,EAAE;AAAA,IAAG,OAAO,aAAa,EAAE;AAAA,IACxE,OAAO,gBAAgB,SAAS;AAAA,EAClC;AACF;AASO,SAAS,qBAAqB,SAAqC;AACxE,QAAM,WAAW,oBAAI,IAAI,CAAC,aAAa,WAAW,eAAe,WAAW,aAAa,gBAAgB,iBAAiB,CAAC;AAC3H,aAAW,QAAQ,QAAQ,WAAW,SAAS,CAAC,GAAG;AACjD,UAAM,QAAQ,KAAK,KAAK,QAAQ,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,UAAQ,QAAQ,SAAS,GAAG;AAC1F,QAAI,MAAM,SAAS,IAAI,EAAG,OAAM,IAAI,MAAM,wDAAwD;AAClG,UAAM,OAAO,MAAM,KAAK,GAAG;AAC3B,QAAI,SAAS,IAAI,IAAI,KAAK,SAAS,0BAA0B,KAAK,WAAW,uBAAuB,KAChG,KAAK,WAAW,mBAAmB,KAAK,SAAS,0CAA0C;AAC7F,YAAM,IAAI,MAAM,2EAA2E;AAAA,IAC7F;AAAA,EACF;AACA,QAAM,SAAS,mBAAmB,SAAS,EAAE,QAAQ,EAAE,cAAc;AAAA,IACnE,4BAA4B,kBAAkB;AAAA,IAC9C;AAAA,EACF,EAAE,EAAE,CAAC;AACL,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,8CAA8C;AAC3E,SAAO;AACT;","names":[]}