Skip to content

skill-end drains before completion timeline enqueue, leaving its latest event unpushed #3198

Closed

Description

@Kkkkkuro

Summary

gstack-skill-end runs its final discover/drain before appending the completion timeline event. gstack-timeline-log also backgrounds its enqueue. A normal full-tier end boundary can therefore return with its own latest completion absent from the remote, and an already tracked timeline remains dirty. A backup checker is correct to report that uncommitted event as not yet durably recoverable; weakening that checker is not the fix.

Reproduced on official main 47d639abffa882b8cbb641d7d1dedf08ecada9ec / v1.91.101, Bun 1.4.2, macOS. No production install was changed. All reproduction Git commits/pushes targeted disposable local bare repositories, with isolated HOME/state/config and synthetic content. No hosted credentials, user text or private repository identifiers are included.

Root cause and proposed fix

  1. Write the completion event before the final skill-end drain.
  2. Wait for the existing enqueue helper to finish instead of backgrounding it. Reordering alone retains a race if the enqueue is still in flight.
  3. Keep the existing full/artifacts-only/off, unattended, transcript-consent, secret-scan and queue-lock gates. This does not authorize publishing behavioral logs in artifacts-only mode.

Official source: skill-end, timeline logger.

Regression evidence

Save the supplied synthetic regression as test/skill-end-completion-durability.test.ts, then run bun test test/skill-end-completion-durability.test.ts.

On unchanged official source: 2 passed, 5 failed. With the two-script patch below: 7 passed, 0 failed (146 assertions). The tests cover existing and new full-tier timelines; artifacts-only with an already tracked timeline (the update stays local and privacy-held); secret plus unconsented transcript holds; unattended no publishing/no new queue entry; a concurrent drain owner retaining the event for the next drain; and a forced delayed enqueue whose completion must precede logger return.

Adjacent existing checks were also attempted: timeline.test.ts, brain-sync.test.ts, transcript-scope-brain-sync.test.ts, gstack-skill-start.test.ts, spawnsync-timeout-tripwire.test.ts: 120 passed, 16 failed in one run. Fifteen old timeline tests launch an unquoted checkout path through execSync and cannot start the command when the checkout path contains spaces; a representative failure also reproduces on pristine source. One CAPY admission case hit its unchanged 5s suite timeout; the same isolated case passes on both pristine and candidate source (~4.1s). The unquoted fixture launch was then corrected to existing execFileSync argument-array calls (no assertion or timeout change); the affected timeline suite plus spawn-timeout tripwire now pass 24/24. That initial suite timeout remains recorded; no clean full-suite run is claimed. Shell syntax, diff whitespace, the official added-code secret scan, and gate inventory passed.

Privacy and limits

The artifacts-only regression deliberately expects a formerly tracked timeline to remain dirty and its new event to be privacy-held. This ordering fix does not untrack past behavioral files or delete remote history after a full-to-artifacts-only downgrade. The current documented privacy-mode setter changes filtering; I did not find a selective, lossless untracking migration preview. No bespoke rm/ignore workaround is proposed here.

The native shell/queue callbacks were exercised; actual Codex/Claude model-driven host callbacks, Windows/Linux, a full free-suite run and production deployment were not tested.

Proposed two-script patch

diff --git a/bin/gstack-skill-end b/bin/gstack-skill-end
index 797a268..dc0d105 100755
--- a/bin/gstack-skill-end
+++ b/bin/gstack-skill-end
@@ -54,15 +54,17 @@ case "$TEL_START" in ''|*[!0-9]*) TEL_START="$_TEL_END" ;; esac
 _TEL_DUR=$(( _TEL_END - TEL_START ))
 [ -n "$SESSION_ID" ] && rm -f "$_GH/analytics/.pending-$SESSION_ID" 2>/dev/null || true
 
+# Record completion before the final drain, including its durable enqueue.
+# The normal sync gates still decide publication: full may sync timelines,
+# artifacts-only retains them locally, and unattended never enqueues or drains.
+"$_BIN/gstack-timeline-log" '{"skill":"'"$SKILL_NAME"'","event":"completed","branch":"'"$(_b=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-'); echo "${_b:-unknown}")"'","outcome":"'"$OUTCOME"'","duration_s":"'"$_TEL_DUR"'","session":"'"$SESSION_ID"'"}' 2>/dev/null || true
+
 # Skill-end artifacts sync (drain + push; formerly its own inline fence).
 if [ "$_SESSION_KIND" != "unattended" ]; then
   "$_BIN/gstack-brain-sync" --discover-new 2>/dev/null || true
   "$_BIN/gstack-brain-sync" --once 2>/dev/null || true
 fi
 
-# Session timeline: local-only, never sent anywhere.
-"$_BIN/gstack-timeline-log" '{"skill":"'"$SKILL_NAME"'","event":"completed","branch":"'"$(_b=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-'); echo "${_b:-unknown}")"'","outcome":"'"$OUTCOME"'","duration_s":"'"$_TEL_DUR"'","session":"'"$SESSION_ID"'"}' 2>/dev/null || true
-
 # Local analytics (gated on telemetry setting).
 if [ "$_TEL" != "off" ]; then
   echo '{"skill":"'"$SKILL_NAME"'","duration_s":"'"$_TEL_DUR"'","outcome":"'"$OUTCOME"'","browse":"'"$USED_BROWSE"'","session":"'"$SESSION_ID"'","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"}' >> "$_GH/analytics/skill-usage.jsonl" 2>/dev/null || true
diff --git a/bin/gstack-timeline-log b/bin/gstack-timeline-log
index 0f24f8a..3d897e1 100755
--- a/bin/gstack-timeline-log
+++ b/bin/gstack-timeline-log
@@ -38,5 +38,7 @@ fi
 
 echo "$INPUT" >> "$GSTACK_HOME/projects/$SLUG/timeline.jsonl"
 
-# gbrain-sync: enqueue for cross-machine sync (no-op if sync is off).
-"$SCRIPT_DIR/gstack-brain-enqueue" "projects/$SLUG/timeline.jsonl" 2>/dev/null &
+# Finish the durable enqueue before returning: skill-end drains immediately
+# after this logger. Backgrounding it can let that drain miss the new event.
+# The helper keeps its off/unattended gates and silent-failure behavior.
+"$SCRIPT_DIR/gstack-brain-enqueue" "projects/$SLUG/timeline.jsonl" 2>/dev/null || true
Synthetic CLI regression (no live service)
/** Completion durability and privacy at the real skill-end boundary.
 * All Git writes stay in disposable local fixtures; no live remote/API. */
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

const BIN = path.resolve(import.meta.dir, '../bin');
const TIMELINE = 'projects/completion-order/timeline.jsonl';
let fixture: string, state: string, remote: string;
let env: Record<string, string>;

function run(bin: string, args: string[] = [], extra: Record<string, string> = {}) {
  const r = spawnSync(path.join(BIN, bin), args, {
    cwd: fixture, env: { ...env, ...extra }, encoding: 'utf-8', timeout: 30_000,
  });
  expect(r.error).toBeUndefined();
  expect(r.status).toBe(0);
  return r;
}
function git(args: string[], dir = state): string {
  const r = spawnSync('git', args, { cwd: dir, env, encoding: 'utf-8', timeout: 30_000 });
  expect(r.status).toBe(0);
  return r.stdout.trim();
}
function write(rel: string, text: string) {
  fs.mkdirSync(path.dirname(path.join(state, rel)), { recursive: true });
  fs.writeFileSync(path.join(state, rel), text);
}
function remoteText(rel: string): string { return git(['show', `main:${rel}`], remote); }
function remotePaths(): string { return git(['ls-tree', '-r', '--name-only', 'main'], remote); }
function queue(): string {
  const dir = path.join(state, '.brain-queue.d');
  return fs.existsSync(dir) ? fs.readdirSync(dir).filter(x => x.endsWith('.json')).map(x => fs.readFileSync(path.join(dir, x), 'utf8')).join('') : '';
}
function seedTrackedTimeline() {
  run('gstack-timeline-log', [JSON.stringify({ skill: 'qa', event: 'started' })]);
  run('gstack-brain-sync', ['--discover-new']);
  run('gstack-brain-sync', ['--once']);
  expect(remoteText(TIMELINE)).toContain('started');
}
function end(extra: Record<string, string> = {}) {
  return run('gstack-skill-end', ['--skill', 'qa', '--outcome', 'success', '--session-id', 'completion-fixture'], extra);
}

beforeEach(() => {
  fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-completion-'));
  state = path.join(fixture, 'state'); remote = path.join(fixture, 'remote.git');
  fs.mkdirSync(state);
  // Do not inherit live state-root overrides, git configuration or API keys.
  const config = path.join(fixture, 'gitconfig');
  fs.writeFileSync(config, '[user]\n name = Fixture\n email = [email protected]\n');
  env = { PATH: process.env.PATH!, HOME: fixture, GSTACK_HOME: state, GSTACK_STATE_ROOT: state,
    GSTACK_PROJECT_SLUG: 'completion-order', GIT_CONFIG_GLOBAL: config, GIT_CONFIG_NOSYSTEM: '1',
    GIT_TERMINAL_PROMPT: '0', GSTACK_SESSION_KIND: 'interactive' };
  git(['init', '--bare', '-q', '-b', 'main', remote], fixture);
  run('gstack-artifacts-init', ['--remote', remote]);
  run('gstack-config', ['set', 'artifacts_sync_mode', 'full']);
  run('gstack-config', ['set', 'telemetry', 'off']);
  run('gstack-config', ['set', 'transcript_ingest_mode', 'off']);
});
afterEach(() => { fs.rmSync(fixture, { recursive: true, force: true }); });

describe('skill-end completion durability', () => {
  test('full: the same final drain pushes a completion into an already tracked timeline', () => {
    seedTrackedTimeline();
    end();
    expect(remoteText(TIMELINE)).toContain('completed');
    expect(git(['status', '--porcelain'])).toBe('');
    expect(queue()).toBe('');
  }, 30_000);

  test('full: a new completion timeline reaches the remote at its first end boundary', () => {
    end();
    expect(remotePaths()).toContain(TIMELINE);
    expect(remoteText(TIMELINE)).toContain('completed');
    expect(queue()).toBe('');
  }, 30_000);

  test('artifacts-only: a formerly tracked behavioral timeline stays local and privacy-held', () => {
    seedTrackedTimeline();
    const before = remoteText(TIMELINE);
    run('gstack-config', ['set', 'artifacts_sync_mode', 'artifacts-only']);
    end();
    expect(remoteText(TIMELINE)).toBe(before);
    expect(fs.readFileSync(path.join(state, TIMELINE), 'utf8')).toContain('completed');
    expect(queue()).toContain(TIMELINE);
    expect(JSON.parse(fs.readFileSync(path.join(state, '.brain-sync-status.json'), 'utf8')).message).toContain('privacy-held');
    // Privacy does not promise a clean old full-tier checkout after downgrade.
    expect(git(['diff', '--name-only'])).toBe(TIMELINE);
  }, 30_000);

  test('full: secret and unconsented transcript holds survive while completion metadata pushes', () => {
    const held = 'projects/completion-order/learnings.jsonl';
    const transcript = 'transcripts/run-fixture-1/session.md';
    const synthetic = ['ghp', 'abcdefghij1234567890abcdef1234567890'].join('_');
    write(held, JSON.stringify({ insight: synthetic }) + '\n');
    write(transcript, '# Synthetic private fixture\n');
    run('gstack-brain-enqueue', [held]); run('gstack-brain-enqueue', [transcript]);
    end();
    expect(remoteText(TIMELINE)).toContain('completed');
    expect(remotePaths()).not.toContain(held); expect(remotePaths()).not.toContain(transcript);
    expect(queue()).toContain(held); expect(queue()).toContain(transcript);
    expect(fs.readFileSync(path.join(state, transcript), 'utf8')).toContain('Synthetic');
    expect(JSON.parse(fs.readFileSync(path.join(state, '.brain-sync-status.json'), 'utf8')).status).toBe('held');
  }, 30_000);

  test('unattended: completion remains local; no drain, push or new queue entry', () => {
    const rel = 'projects/completion-order/ceo-plans/fixture.md';
    write(rel, '# Fixture\n'); run('gstack-brain-enqueue', [rel]);
    const beforeQueue = queue(), head = git(['rev-parse', 'main'], remote);
    expect(end({ GSTACK_SESSION_KIND: 'unattended' }).stdout).toContain('ARTIFACTS_SYNC: skipped');
    expect(git(['rev-parse', 'main'], remote)).toBe(head); expect(queue()).toBe(beforeQueue);
    expect(fs.readFileSync(path.join(state, TIMELINE), 'utf8')).toContain('completed');
    expect(fs.existsSync(path.join(state, 'analytics/skill-usage.jsonl'))).toBe(false);
  }, 30_000);

  test('concurrent drain owner: completion remains queued and a later drain publishes it', async () => {
    const holder = Bun.spawn(['bash', '-c', '. "$1"; gstack_brain_lock_acquire "$2" try || exit 9; echo locked; read -r release; gstack_brain_lock_release', '_', path.join(BIN, 'gstack-brain-lock.sh'), state],
      { env, cwd: fixture, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
    try {
      const reader = holder.stdout.getReader();
      expect(new TextDecoder().decode((await reader.read()).value)).toContain('locked');
      end();
      expect(queue()).toContain(TIMELINE); expect(remotePaths()).not.toContain(TIMELINE);
    } finally { holder.stdin.write('release\n'); holder.stdin.end(); expect(await holder.exited).toBe(0); }
    run('gstack-brain-sync', ['--once']);
    expect(remoteText(TIMELINE)).toContain('completed'); expect(queue()).toBe('');
  }, 30_000);

  test('logger returns only after a delayed enqueue makes its spool record durable', () => {
    const shadow = path.join(fixture, 'bin'); fs.mkdirSync(shadow);
    for (const f of fs.readdirSync(BIN)) { fs.symlinkSync(path.join(BIN, f), path.join(shadow, f)); }
    for (const f of ['gstack-timeline-log', 'gstack-brain-enqueue']) { fs.unlinkSync(path.join(shadow, f)); }
    fs.copyFileSync(path.join(BIN, 'gstack-timeline-log'), path.join(shadow, 'gstack-timeline-log'));
    const marker = path.join(fixture, 'enqueue-done');
    fs.writeFileSync(path.join(shadow, 'gstack-brain-enqueue'), '#!/bin/sh\nsleep 0.4\n' + 'printf done > "$ENQUEUE_MARKER"\n', { mode: 0o755 });
    const r = spawnSync(path.join(shadow, 'gstack-timeline-log'), [JSON.stringify({ skill: 'qa', event: 'completed' })],
      { cwd: fixture, env: { ...env, ENQUEUE_MARKER: marker }, stdio: 'ignore', timeout: 30_000 });
    expect(r.status).toBe(0); expect(fs.existsSync(marker)).toBe(true);
  }, 30_000);
});
Test-launcher correction for checkouts with spaces (no production behavior change)
diff --git a/test/timeline.test.ts b/test/timeline.test.ts
index eb4303c..ab1e9f9 100644
--- a/test/timeline.test.ts
+++ b/test/timeline.test.ts
@@ -1,5 +1,5 @@
 import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
-import { execFileSync, execSync, spawnSync, ExecSyncOptionsWithStringEncoding } from 'child_process';
+import { execFileSync, spawnSync, ExecSyncOptionsWithStringEncoding } from 'child_process';
 import * as fs from 'fs';
 import * as path from 'path';
 import * as os from 'os';
@@ -18,7 +18,7 @@ function runLog(input: string, opts: { expectFail?: boolean } = {}): { stdout: s
     timeout: 15000,
   };
   try {
-    const stdout = execSync(`${BIN}/gstack-timeline-log '${input.replace(/'/g, "'\\''")}'`, execOpts).trim();
+    const stdout = execFileSync(path.join(BIN, 'gstack-timeline-log'), [input], execOpts).trim();
     return { stdout, exitCode: 0 };
   } catch (e: any) {
     if (opts.expectFail) {
@@ -28,7 +28,7 @@ function runLog(input: string, opts: { expectFail?: boolean } = {}): { stdout: s
   }
 }
 
-function runRead(args: string = ''): string {
+function runRead(args: string[] = []): string {
   const execOpts: ExecSyncOptionsWithStringEncoding = {
     cwd: ROOT,
     env: { ...process.env, GSTACK_HOME: tmpDir },
@@ -36,7 +36,7 @@ function runRead(args: string = ''): string {
     timeout: 15000,
   };
   try {
-    return execSync(`${BIN}/gstack-timeline-read ${args}`, execOpts).trim();
+    return execFileSync(path.join(BIN, 'gstack-timeline-read'), args, execOpts).trim();
   } catch {
     return '';
   }
@@ -155,7 +155,7 @@ describe('gstack-timeline-read', () => {
     runLog(JSON.stringify({ skill: 'review', event: 'completed', branch: 'feature-a', outcome: 'approved', ts: '2026-03-28T10:00:00Z' }));
     runLog(JSON.stringify({ skill: 'ship', event: 'completed', branch: 'feature-b', outcome: 'merged', ts: '2026-03-28T11:00:00Z' }));
 
-    const output = runRead('--branch feature-a');
+    const output = runRead(['--branch', 'feature-a']);
     expect(output).toContain('review');
     expect(output).not.toContain('feature-b');
   });
@@ -176,8 +176,8 @@ describe('gstack-timeline-read', () => {
       runLog(JSON.stringify({ skill: 'review', event: 'completed', branch: 'main', outcome: 'approved', ts: `2026-03-2${i}T10:00:00Z` }));
     }
 
-    const unlimited = runRead('--limit 20');
-    const limited = runRead('--limit 2');
+    const unlimited = runRead(['--limit', '20']);
+    const limited = runRead(['--limit', '2']);
 
     // Count event lines (lines starting with "- ")
     const unlimitedEvents = unlimited.split('\n').filter(l => l.startsWith('- ')).length;

Activity

  1. capy-ai commented on Oct 16, 2026

    @capy-ai
    Contributor

    Fixed in v1.91.106.0 (main 3e8b34d, wave PR #3209). gstack-skill-end writes its completion event before the final drain, and gstack-timeline-log waits for its enqueue. Adopted from your patch and regression test; thank you for the diagnosis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions